之前公司导出Excel表采用的是前端导出,但是由于优化了查询列表,查询的列表是好几个接口一起完成的,这样显然不适合再用前端导出,尝试着采用后端导出。
公司使用的是springboot+jpa。
首先需要做的就是将想要导出的内容先查询出来,根据筛选条件联表查询,结果集封装到dto后(也可以不封装直接使用List<object[]>,封装更利于理解),我们再开始设计Excel表的内容,首先创建Excel对象
HSSFWorkbook wb = new HSSFWorkbook();
再建立新的sheet对象(excel的表单)
HSSFSheet sheet = wb.createSheet("sheetname");//填入表名
再接着就可以创建行了,在第一行里写入表头
HSSFRow row1 = sheet.createRow(0);
// 创建第一行设置单元格内容
row1.createCell(0).setCellValue("row1");
row1.createCell(1).setCellValue("row2");
row1.createCell(2).setCellValue("row3");
row1.createCell(3).setCellValue("row4");
row1.createCell(4).setCellValue("row5");
row1.createCell(5).setCellValue("row6");
再根据列表条数循环插入每一行的数据
for (int i = 0; i < list.size(); i++) {
HSSFRow row = sheet.createRow(i + 1);
ExportListDto exportListDto = list.get(i);
// 创建单元格并设置单元格内容
row.createCell(0).setCellValue(exportListDto.getCode());
row.createCell(1).setCellValue(exportListDto.getName());
row.createCell(2).setCellValue(exportListDto.getStatusName());
row.createCell(3).setCellValue(exportListDto.getOrderCode());
row.createCell(4).setCellValue(exportListDto.getOrderProgressName());
row.createCell(5).setCellValue(exportListDto.getOrderStatusName());
}
这个时候一个简单的Excel表单就完成了,再输出即可
// 输出Excel文件
ServletOutputStream outputStream = null;
try {
outputStream = response.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
response.setHeader("Content-disposition", "attachment; filename=信息表.xls");
response.setContentType("application/vnd.ms-excel;charset=utf-8");
try {
wb.write(outputStream);
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}