POI excel导出与easyexcel导入实践
(一) 准备
1.0 pom依赖
备注:由于easyExcel自带依赖于3.17的poi,所以如果项目其它地方映入了其它版本的poi,就会导致easyExcel导出失败等一系列问题,主要原因是因为poi版本冲突导致的
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
<!-- <version>3.6</version>-->
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
<!-- <version>3.6</version>-->
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.1.2</version>
<!-- <version>3.6</version>-->
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/easyexcel -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>net.sf.saxon</groupId>
<artifactId>saxon-dom</artifactId>
<version>8.7</version>
<scope>compile</scope>
</dependency>
2.0 接口controller层:
@PostMapping("/export/hasDeliveredOrder")
public BaseResponse exportHasDeliveredOrder(HttpServletResponse response, @RequestBody HasDeliverExportReq hasDeliverExportReq) {
log.info("开始导出已发货订单列表");
List<HasDeliverResp> list = localSpeService.exportHasDeliveredOrder(hasDeliverExportReq);
// 创建excel
HSSFWorkbook wk = new HSSFWorkbook();
// 创建一张工作表
HSSFSheet sheet = wk.createSheet();
// 2
sheet.setColumnWidth(0, 5000);
HSSFRow row = sheet.createRow(0);
HSSFCellStyle style = wk.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER);//水平居中
// style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//垂直居中 POI版本为3.9
style.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
style.setWrapText(true);//自动换行
style.setIndention((short) 5);//缩进
HSSFFont font = wk.createFont();
font.setFontName("微软雅黑");//设置字体名称
font.setFontHeightInPoints((short) 10);//设置字号
style.setFont(font);
// 创建第一行的第一个单元格
// 单元格写值
HSSFCell cell = row.createCell((short) 0);
cell.setCellValue("订单编号");
cell = row.createCell((short) 1);
cell.setCellValue("订单状态");
cell = row.createCell((short) 2);
cell.setCellValue("用户id");
cell = row.createCell((short) 3);
cell.setCellValue("用户昵称");
cell = row.createCell((short) 4);
cell.setCellValue("商品名称");
cell = row.createCell((short) 5);
cell.setCellValue("商品套餐");
cell = row.createCell((short) 6);
cell.setCellValue("套餐数量");
cell = row.createCell((short) 7);
cell.setCellValue("收货地址");
cell = row.createCell((short) 8);
cell.setCellValue("收货人");
cell = row.createCell((short) 9);
cell.setCellValue("联系方式");
cell = row.createCell((short) 10);
cell.setCellValue("发货时间");
cell = row.createCell((short) 11);
cell.setCellValue("物流公司");
cell = row.createCell((short) 12);
cell.setCellValue("物流单号");
// 创建第一行
for (short i = 0; i < list.size(); i++) {
row = sheet.createRow(i + 1);
row.createCell(0).setCellValue(list.get(i).getOrderNumber());
row.createCell(