Apache POI 第六讲之利用Excel模板实现数据的批量导出

来源:互联网 发布:mac颜色配置文件下载 编辑:程序博客网 时间:2024/05/13 00:49

有时候我们在做项目时,有些项目需要生成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.查看结果

这里写图片描述

这里写图片描述

这里写图片描述

0 0
原创粉丝点击