1.首先导入poi依赖,注意与spring版本别冲突
spring 4.00使用poi 3及以上的
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.17</version>
</dependency>
2.编写Java代码
@PostMapping("/export")
public void exportA(int pageNum,int pageSize,HttpServletResponse response){
//分页查询出数据列表
PageInfo<ClmRoutineextract> clmRoutineextractPageInfo = clmRoutineextractService.queryAllByLimit(pageNum, pageSize);
//查出的信息转换List
List<ClmRoutineextract> list = clmRoutineextractPageInfo.getList();
//创建工作簿
XSSFWorkbook workbook=new XSSFWorkbook();
//创建sheet页
XSSFSheet sheet= workbook.createSheet("bx");
//创建行
XSSFRow row= sheet.createRow(0);
//单元格
XSSFCell cell=row.createCell(0);
//设置表头样式
CellStyle headerStyle = workbook.createCellStyle();
// 单元格样式
CellStyle cellStyle = workbook.createCellStyle();
//创建一个DataFormat对象
XSSFDataFormat format = workbook.createDataFormat();
cellStyle.setDataFormat(format.getFormat("@"));
cell.setCellStyle(cellStyle);
//设置自动换行
cellStyle.setWrapText(true);
//创建行标题
row.createCell(0).setCellValue("ID");
row.createCell(1).setCellValue("姓名");
row.createCell(2).setCellValue("性别");
row.createCell(3).setCellValue("年龄");
//数据填充
for (int i = 0; i < list.size(); i++) {
ClmRoutineextract clmRoutineextract = list.get(i);
row= sheet.createRow(i+1);
row.createCell(0).setAsActiveCell();
row.createCell(0).setCellValue(String.valueOf(clmRoutineextract.getId()));
row.createCell(1).setCellValue(clmRoutineextract.getZnRate());
row.createCell(2).setCellValue(clmRoutineextract.getZnSize());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String time= sdf.format(clmRoutineextract.getModifyTime());
row.createCell(3).setCellValue(time);
}
//设置响应头
response.setCharacterEncoding("utf-8");
response.setContentType("application/vnd.ms-excel");
response.addHeader("Content-Disposition", "attachment;filename=fileName"+"aa.xlsx");
//写入excel
try {
workbook.write(response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
3.注意事项
1.比如单号我们一般都是很长的数字,在导出后会变成科学计数法,我们想要变成数显示需要将数转换成string类型再set进去,同时单元格也需要设置成文本(如上述的创建一个DataFormat对象)
2.日期也同样需要转换成日期类型,要不导出后日期会变成一串数字