有时候我们在做项目时,有些项目需要生成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') ;
}