您的位置:首页 > 运维架构 > Apache

Apache POI 第五讲之利用POI 实现数据的批量导出

2016-07-06 20:41 645 查看
有时候我们在做项目时,有些项目需要生成Microsoft Excel文件格式的报告。有时,甚至希望将Excel文件作为输入数据。这是我们需要用到Apache POI 。例如,一个公司开发的应用程序将财务部门需要所有输出生成自己的Excel。

利用 POI 实现数据的批量导出

[b]1.编写导出工具类[/b]

public class ExcelUtil {

public static void fillExcelData(ResultSet rs,Workbook wb,String[] headers)throws Exception{
int rowIndex=0;
Sheet sheet=wb.createSheet();
Row row=sheet.createRow(rowIndex++);
for(int i=0;i<headers.length;i++){
row.createCell(i).setCellValue(headers[i]);
}
while(rs.next()){
row=sheet.createRow(rowIndex++);
for(int i=0;i<headers.length;i++){
row.createCell(i).setCellValue(rs.getObject(i+1).toString());
}
}
}
}


public class ResponseUtil {

public static void write(HttpServletResponse response,Object o)throws Exception{
response.setContentType("text/html;charset=utf-8");
PrintWriter out=response.getWriter();
out.print(o.toString());
out.flush();
out.close();
}

public static void export(HttpServletResponse response,Workbook wb,String fileName)throws Exception{
response.setHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes("utf-8"),"iso8859-1"));
response.setContentType("application/ynd.ms-excel;charset=UTF-8");
OutputStream out=response.getOutputStream();
wb.write(out);
out.flush();
out.close();
}

}


[b]2.编写action类导出方法[/b]

public String export()throws Exception{
Connection con=null;
try {
con=dbUtil.getCon();
Workbook wb=new HSSFWorkbook();
String headers[]={"编号","姓名","电话","Email","QQ"};
ResultSet rs=userDao.userList(con, null);
ExcelUtil.fillExcelData(rs, wb, headers);
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;
}


[b]3.编写页面[/b]

function exportUser(){
window.open('user!export') ;
}


[b]5.查看结果[/b]







本实例用了easyui 与 struts2 ,无关紧要,简单的把相关POI代码粘贴出来,仅供参考。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  poi easyui 数据 apache