报表技术之Excel格式报表生成(POI)
程序员文章站
2022-04-30 20:36:08
...
报表技术之Excel格式报表生成(POI)
1.找到你的页面的导出Excel的按钮
2.给导出按钮添加事件
3. 编写 ReportAction 添加 exportXls 方法
- POI 生成 Excel 步骤写 Excel 过程一样,新建 Excel 文档 –新建 Sheet – 新建 Row –
新建 Cell 单元格 – 写单元格数据 - POI 生成 HSSF (xls)和 XSSF (xlsx)
//导出Excel报表
@Action(value = "report_exportXls")
public String exportXls() throws IOException {
//查出满足条件的数据
List<WayBill> wayBills = wayBillService.findWayBills(model);
//生成Excel
// HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
// HSSFSheet sheet = hssfWorkbook.createSheet("运单数据");
//创建工作簿
XSSFWorkbook xssfWorkbook = new XSSFWorkbook();
XSSFSheet sheet = xssfWorkbook.createSheet("运单数据");
//创建Row
XSSFRow row = sheet.createRow(0);
row.createCell(0).setCellValue("运单号");
row.createCell(1).setCellValue("寄件人");
row.createCell(2).setCellValue("寄件人电话");
row.createCell(3).setCellValue("寄件人地址");
row.createCell(4).setCellValue("收件人");
row.createCell(5).setCellValue("收件人电话");
row.createCell(6).setCellValue("收件人地址");
for (WayBill wayBill : wayBills) {
XSSFRow xssfRow = sheet.createRow(sheet.getLastRowNum()+1);
xssfRow.createCell(0).setCellValue(wayBill.getWayBillNum());
xssfRow.createCell(1).setCellValue(wayBill.getSendName());
xssfRow.createCell(2).setCellValue(wayBill.getSendMobile());
xssfRow.createCell(3).setCellValue(wayBill.getSendAddress());
xssfRow.createCell(4).setCellValue(wayBill.getRecName());
xssfRow.createCell(5).setCellValue(wayBill.getRecMobile());
xssfRow.createCell(6).setCellValue(wayBill.getRecAddress());
}
//下载导出
//设置头信息
ServletActionContext.getResponse().setContentType("application/vnd.ms-excel");
String filename = "运单数据.xlsx";
String agent = ServletActionContext.getRequest().getHeader("user-agent");
filename = FileUtils.encodeDownloadFilename(filename, agent);
//处理中文乱码
//String filename = new String(filename.getBytes(),"ISO-8859-1");
ServletActionContext.getResponse().setHeader("Content-Disposition", "attachment;filename="+filename);
ServletOutputStream outputStream = ServletActionContext.getResponse().getOutputStream();
xssfWorkbook.write(outputStream);
//关闭
xssfWorkbook.close();
return NONE;
}
4.编写Service代码
无条件查询所有数据不分页
有条件,查询分页数据,第一页所有数据
结果展示
导出的Excel文件展示