Apache POI 第六講之利用Excel模板實現數據的批量導出

有時候我們在做項目時,有些項目需要生成Microsoft Excel文件格式的報告。有時,甚至希望將Excel文件作爲輸入數據。這是我們需要用到Apache POI 。例如,一個公司開發的應用程序將財務部門需要所有輸出生成自己的Excel。

利用Excel模板實現數據的批量導出

1.編寫導出工具類
public static Workbook fillExcelDataWithTemplate(ResultSet rs ,String templateFile) throws Exception {
        InputStream inp = ExcelUtil.class.getResourceAsStream("/com/wenteryan/template/"+templateFile) ;
        POIFSFileSystem fs = new POIFSFileSystem(inp) ;
        Workbook wb = new HSSFWorkbook(fs) ;
        Sheet sheet = wb.getSheetAt(0) ;
        int cellNums = sheet.getRow(0).getLastCellNum() ;
        int rowIndex = 1 ;
        while(rs.next()) {
            Row row = sheet.createRow(rowIndex++) ;
            for(int i=0; i<cellNums; i++) {
                row.createCell(i).setCellValue(rs.getObject(i+1).toString()) ;
            }
        }
        return wb ;
    }
2.編寫action類導出方法
public String export2() throws Exception{
        Connection con=null;
        try {
            con=dbUtil.getCon();
            Workbook wb= ExcelUtil.fillExcelDataWithTemplate(userDao.userList(con, null), "userExporTemplate.xls") ;
            ResponseUtil.export(ServletActionContext.getResponse(), wb, "利用模板導出excel.xls");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            try {
                dbUtil.closeCon(con);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return null;
    }
3.編寫頁面
function exportUser2(){
    window.open('user!export2') ;
}
5.查看結果

這裏寫圖片描述

這裏寫圖片描述

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章