使用hutool工具类,快速导出Excel表格
public void export(List list,HttpServletResponse response){
// 1.获取ExcelWriter对象
ExcelWriter writer = ExcelUtil.getBigWriter();
// 2.写出表头
// 自定义标题别名
writer.addHeaderAlias("name", "姓名");
writer.addHeaderAlias("age", "年龄");
writer.addHeaderAlias("hobby", "爱好");
// ...
// 3.定义表头单元格样式(可选)
StyleSet style = writer.getStyleSet();
CellStyle headCellStyle = style.getHeadCellStyle();
// 自动换行
headCellStyle.setWrapText(true);
// 水平居中
headCellStyle.setAlignment(HorizontalAlignment.CENTER);
// 上下居中
headCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
// 设置表头字体大小
Font headFont = writer.createFont();
headFont.setFontName("宋体");
headFont.setFontHeightInPoints((short) 15); // 设置字体大小为15磅
headCellStyle.setFont(headFont);
// 4.定义内容单元格样式(可选)
CellStyle cellStyle = style.getCellStyle();
cellStyle.setAlignment(HorizontalAlignment.LEFT);
// 设置字体大小
Font font = writer.createFont();
font.setFontName("宋体");
cellStyle.setFont(font);
// 5.其他设置(可选)
// 只写出设置别名的属性
writer.setOnlyAlias(true);
// 冻结行
writer.setFreezePane(1);
// 6.写入数据 设置列宽
writer.write(list);
writer.autoSizeColumnAll();
// 7.开启筛选(可选)
// 这里数值为列数
String rangeString = CellReference.convertNumToColString(3) + "1";
CellRangeAddress filterRange = CellRangeAddress.valueOf("A1:" + rangeString);
writer.getSheet().setAutoFilter(filterRange);
// 8.导出
response.setCharacterEncoding(CharsetUtil.UTF_8);
response.setHeader("Content-Disposition","attachment;filename=");
response.setContentType("application/-excel;" + CharsetUtil.UTF_8);
try (ServletOutputStream outputStream = response.getOutputStream()) {
writer.flush(outputStream);
writer.close();
} catch (Exception e) {
log.warn("批量导出出错:{}", e.getMessage());
}
}