easyexcel多行不同的表头导出(多表格不同表头)
一、效果展示
二、代码
/**
* 导出月度报表数据信息
*/
@ApiOperation(value = "导出月度报表数据信息")
@Log(title = "导出月度报表", businessType = BusinessType.EXPORT)
@RequestMapping("/exportMonthChart")
public void exportMonthChart(HttpServletResponse response) {
try {
tableWrite(response,input);
} catch (IOException e) {
e.printStackTrace();
}
}
public void tableWrite(HttpServletResponse response) throws IOException {
MonthChartOutput output = lsDeviceInfoService.monthChart(input);
WriteSheet writeSheet = EasyExcel.writerSheet("设备月度报表").needHead(Boolean.FALSE).build();
// 这里必须指定需要头,table 会继承sheet的配置,sheet配置了不需要,table 默认也是不需要
WriteTable writeTable0 = EasyExcel.writerTable(0).needHead(Boolean.TRUE).head(ExportVO.class).build();
WriteTable writeTable1 = EasyExcel.writerTable(1).needHead(Boolean.TRUE).head(ExportVO.class).build();
WriteTable writeTable2 = EasyExcel.writerTable(2).needHead(Boolean.TRUE).head(DemoData.class).build();
// 生成无表头的内容
List<List<String>> headList = Lists.newArrayList();
headList.add(Lists.newArrayList("自定义表头1","自定义表头2","自定义表头3"));
// 生成有表头的内容
List<ExportVO> list = Lists.newArrayList();
for (int i = 1; i < 10; i++) {
list.add(ExportVO.builder().heat1("第"+i+"行内容")
.heat2("第"+i+"行内容")
.heat3("第"+i+"行内容")
.heat4("第"+i+"行内容")
.heat5("第"+i+"行内容")
.build());
}
String fileName = URLEncoder.encode("销售表现趋势分析-"+ System.currentTimeMillis()+".xlsx", "UTF-8");
response.setCharacterEncoding("UTF-8");
response.setHeader("content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
response.setHeader("filename", fileName);
ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
// 第一次写入
excelWriter.write(headList, writeSheet, writeTable0);
// 第二次写入会创建头,然后在第一次的后面写入数据
excelWriter.write(list, writeSheet, writeTable1);
excelWriter.write(data(), writeSheet, writeTable2);
excelWriter.finish();
}
private List<DemoData> data() {
List<DemoData> list = ListUtils.newArrayList();
for (int i = 0; i < 10; i++) {
DemoData data = new DemoData();
data.setString("字符串" + i);
data.setDate(new Date());
data.setDoubleData(0.56);
list.add(data);
}
return list;
}
实体DemoData 代码:
@Getter
@Setter
@EqualsAndHashCode
public class DemoData {
@ExcelProperty("字符串标题")
private String string;
@ExcelProperty("日期标题")
private Date date;
@ExcelProperty("数字标题")
private Double doubleData;
/**
* 忽略这个字段
*/
@ExcelIgnore
private String ignore;
}
实体DemoData 代码:
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@HeadRowHeight(18)
@ContentRowHeight(15)
@ColumnWidth(16)
public class ExportVO {
@ExcelProperty("表头1")
private String heat1;
@ExcelProperty("表头2")
private String heat2;
@ExcelProperty("表头3")
private String heat3;
@ExcelProperty("表头4")
private String heat4;
@ExcelProperty("表头5")
private String heat5;
}