POI ワークブック、シート、セルの作成
ナビゲーションに移動
検索に移動
POI ワークブック、シート、セルの作成
package info.typea.sample.poi.test; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFRichTextString; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.poifs.filesystem.POIFSFileSystem; public class POITest { public static void main(String[] args) { try { POITest me = new POITest(); File f = new File("c:\\work\\poi.xls"); if (!f.exists()) { // Bookを作成 me.createNewWorkBook(f); // Sheetを追加 String[] sheets = {"POIにより追加(1)","POIにより追加(2)"}; for (String s : sheets) { me.addNewWorkSheet(f, s); } } String[][] data = { {"A1", "B1" , "C1" , "D", "E"} ,{"A2", "B2" , "C2" , "D1"} ,{"A3", "B3" } ,{"A4", } }; me.writeTableData(f, 0, data); System.out.println("finish."); } catch (Exception e) { e.printStackTrace(); } } /** * ワークブックの作成 * @param file * @throws Exception */ public void createNewWorkBook(File file) throws Exception { FileOutputStream out = new FileOutputStream(file); HSSFWorkbook wb = new HSSFWorkbook(); wb.write(out); out.close(); } /** * シートの追加 * @param file * @param shtName * @throws Exception */ public void addNewWorkSheet(File file, String shtName) throws Exception { POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(file)); HSSFWorkbook wb = new HSSFWorkbook(fs); wb.createSheet(shtName); FileOutputStream out = new FileOutputStream(file); wb.write(out); out.close(); } /** * セルを作成し、データの書き込み * @param file * @param shtId * @param data * @throws Exception */ public void writeTableData(File file, int shtId, String[][] data) throws Exception { POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(file)); HSSFWorkbook wb = new HSSFWorkbook(fs); HSSFSheet sht = wb.getSheetAt(shtId); int r=0; for (String[] row : data) { HSSFRow xlsrow = sht.createRow(r++); short c=0; for (String col : row) { HSSFCell xlscell = xlsrow.createCell(c++); xlscell.setCellValue(new HSSFRichTextString(col)); } } FileOutputStream out = new FileOutputStream(file); wb.write(out); out.close(); } }
© 2006 矢木浩人