一般Excel不需要复杂的数据格式导出,只是在表头上略有区别,下面展示单行和多行表头Excel导出
1、单行表头
例如:Excel表头只有单行,那就只需要使用注解@ExcelProperty即可实现
① 添加依赖
首先,在 pom.xml 中添加 EasyExcel 的依赖:
<!-- EasyExcel 依赖 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.3.3</version>
</dependency>
② 定义数据模型
在数据模型 EnergyTimeDetailVO需要导出的字段上添加注解信息@ExcelProperty
@Data
public class EnergyTimeDetailVO {
@ApiModelProperty("时间")
@ExcelProperty(value = "时间", index = 0)
private String time;
@ApiModelProperty("起始读数")
@ExcelProperty(value = "起始读数", index = 1)
private BigDecimal startRead;
@ApiModelProperty("终止读数")
@ExcelProperty(value = "终止读数", index = 2)
private BigDecimal endRead;
@ApiModelProperty("总用量")
@ExcelProperty(value = "总用量", index = 3)
private BigDecimal usage;
}
③ 编写导出逻辑
public class EasyExcelUtils {
public static void downloadExcel(String fileName, String sheetName, Class clz, List list, HttpServletResponse response) throws IOException {
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
fileName = URLEncoder.encode(fileName, "UTF-8");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ";" + "filename*=utf-8''" + fileName + ".xlsx");
EasyExcel.write(response.getOutputStream(), clz)
.sheet(sheetName)
.registerWriteHandler(new CustomCellWriteWidthStrategy()) /*自适应列宽*/
.registerWriteHandler(new CustomCellWriteHeightStrategy()) /*自适应行高*/
.doWrite(list);
}
}
自适应列宽CustomCellWriteWidthStrategy类和自适应行高CustomCellWriteHeightStrategy类,在这篇文章中:Java使用EasyExcel自定义合并(横纵合并)、自定义行高列宽、自适应行高列宽工具、自定义样式Excel导出_easyexcel 横向合并-CSDN博客
④ Excel导出
public void exportEnergyDetail(UseEnergyComparedMeterDTO param, HttpServletResponse response) {
String fileName = "用能明细" + DateUtil.format(new Date(), DatePattern.PURE_DATE_FORMAT);
try {
List<EnergyTimeDetailVO> detailList = this.energyComparedDetail(param);
EasyExcelUtils.downloadExcel(fileName, "数据明细", EnergyTimeDetailVO.class, detailList, response);
} catch (Exception e) {
log.error("用能明细:{}", e.getMessage());
}
}
⑤ 效果展示:
2、多行表头
如果数据标头为多行,如下方:
就只需要要修改导出的类EnergyTimeDetailVO上的注解信息@ExcelProperty:
@Data
public class EnergyTimeDetailVO {
@ApiModelProperty("时间")
@ExcelProperty(value = "时间", index = 0)
private String time;
@ApiModelProperty("起始读数")
@ExcelProperty(value = {"读数", "起始读数"}, index = 1)
private BigDecimal startRead;
@ApiModelProperty("终止读数")
@ExcelProperty(value = {"读数", "终止读数"}, index = 2)
private BigDecimal endRead;
@ApiModelProperty("总用量")
@ExcelProperty(value = "总用量", index = 3)
private BigDecimal usage;
}
其他代码不变,撒花✿✿ヽ(°▽°)ノ✿,完结……
如果是动态表头,就是非固定表头的Excel可以参照这篇文章:
Java使用EasyExcel生成动态表头和多Sheet数据的Excel_easyexcel 动态表头和动态数据-CSDN博客