2010年3月11日木曜日

JavaでExcelのWorkbookを生成する

忘れないようにメモ
色々な所からサンプル引っ張ってきたりしてるので
超つぎはぎな感じで。
そしてエラー処理は超適当('A`)

使ってるのはおなじみ Apache POIだす。


    public void createWorkbook(String path, List source) throws IOException {
        String fileName = path;
        FileOutputStream out = new FileOutputStream(fileName);
        Workbook wb = this.getWorkbook(fileName);
        Sheet s = wb.createSheet();
        s.setColumnWidth(0, 256);
        s.setColumnWidth(1, 256);
        
        Row r = null;

        int rownum;
 
        // create body
        int buf = 2;
        rownum = 8;
        for (String[] list: source) {
            r = s.createRow(rownum);
            Cell cell = r.createCell(0);
            int localCol = buf;
            for (String val : list) {
                cell = r.createCell(localCol);
                cell.setCellValue(val.trim());
                
                localCol++;
            }
            
            rownum++;
        }
        
        r = s.createRow(rownum);
        Cell cell = r.createCell(3);
        cell.setCellFormula("COUNTA(D9:D43)");
        
        wb.write(out);
        out.close();
    }

0 件のコメント: