【EasyExcel】的使用技巧,随时间推移进行更新:
- 2023-12-26——【使excel中的公式生效】
- 2023-12-28——【ExportUtil,通用方法导出Excel】
提示:以下是本篇文章正文内容
ExcelWriter excelWriter = EasyExcel.write(out).withTemplate(in).build();
// 导出逻辑
…………
…………
// 使excel中的公式生效
excelWriter.writeContext().writeWorkbookHolder().getWorkbook().setForceFormulaRecalculation(true);
代码讲解:
首先获取excelWriter
,然后导出,然后最后通过excelWriter
获取到workbook
,然后设置对应的参数为true
,即可使excel模板中原有的公式生效,如sum(a1:a5)
之类的原公式。
getOutputStream()方法:
/**
* 导出文件时为Writer生成OutputStream.
*
* @param fileName 文件名
* @param response response
* @return 输出流
*/
public static OutputStream getOutputStream(String fileName, HttpServletResponse response) {
try {
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xlsx");
response.setHeader("Pragma", "public");
response.setHeader("Cache-Control", "no-store");
response.addHeader("Cache-Control", "max-age=0");
return response.getOutputStream();
} catch (Exception e) {
throw new ServiceException(ResultCode.FAILURE, "导出失败");
}
}
模板是存在于resource目录下的固定的模板文件
/**
* 下载模板
*
* @param response response
* @param fileName 模板文件名称
*/
public static void downloadTemplate(HttpServletResponse response, String fileName) {
try (OutputStream out = getOutputStream(fileName, response);
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("template/" + fileName + ".xlsx");
ExcelWriter excelWriter = EasyExcel.write(out).withTemplate(in).build()) {
excelWriter.finish();
} catch (Exception e) {
log.error("模板下载失败:{}", e.getLocalizedMessage());
throw new ServiceException(ResultCode.FAILURE, "模板下载失败");
}
}
模板是存在于resource目录下的固定的模板文件,使用对应模板的数据进行导出
/**
* 导出excel,使用模板
*
* @param response response
* @param templateName 模板文件名
* @param data 数据
* @param exportName 导出文件名
*/
public static void excelExportByTemplate(HttpServletResponse response, String templateName, Object data, String exportName) {
try (OutputStream out = getOutputStream(exportName, response);
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("template/" + templateName + ".xlsx")) {
EasyExcel.write(out).withTemplate(in).sheet()
.registerWriteHandler(ExportUtil.getStyleStrategy())
.doFill(data);
} catch (Exception e) {
log.error("导出失败:{}", e.getLocalizedMessage());
throw new ServiceException(ResultCode.FAILURE, "导出失败");
}
}
使用easyExcel提供的注解标注dto后,进行导出
/**
* 导出excel,使用注解
*
* @param response response
* @param fileName 文件名
* @param data 数据
* @param clazz 实体类
*/
public static void excelExportByAnnotation(HttpServletResponse response, String fileName, List<?> data, Class<?> clazz) {
try (OutputStream out = getOutputStream(fileName, response)) {
EasyExcel.write(out, clazz).sheet()
.registerWriteHandler(ExportUtil.getStyleStrategy()) // getStyleStrategy()是下一个代码块中的导出策略
.doWrite(data);
} catch (Exception e) {
log.error("导出失败:{}", e.getLocalizedMessage());
throw new ServiceException("导出失败");
}
}
/**
* 导出策略
*/
public static HorizontalCellStyleStrategy getStyleStrategy() {
// 头的策略 样式调整
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
// 头背景色
headWriteCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
WriteFont headWriteFont = new WriteFont();
// 头字号
headWriteFont.setFontHeightInPoints((short) 15);
// 字体样式
headWriteFont.setFontName("宋体");
headWriteCellStyle.setWriteFont(headWriteFont);
// 自动换行
headWriteCellStyle.setWrapped(false);
// 设置细边框
headWriteCellStyle.setBorderBottom(BorderStyle.THIN);
headWriteCellStyle.setBorderLeft(BorderStyle.THIN);
headWriteCellStyle.setBorderRight(BorderStyle.THIN);
headWriteCellStyle.setBorderTop(BorderStyle.THIN);
// 设置边框颜色
headWriteCellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
headWriteCellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
headWriteCellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
headWriteCellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());
// 水平对齐方式/垂直对齐方式
headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
headWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
///
// 内容的策略 宋体
WriteCellStyle contentStyle = new WriteCellStyle();
// 设置垂直居中
contentStyle.setVerticalAlignment(VerticalAlignment.CENTER);
// 设置水平居中
contentStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
WriteFont contentWriteFont = new WriteFont();
// 内容字号
contentWriteFont.setFontHeightInPoints((short) 12);
// 字体样式
contentWriteFont.setFontName("宋体");
contentStyle.setWriteFont(contentWriteFont);
// 设置细边框
contentStyle.setBorderBottom(BorderStyle.THIN);
contentStyle.setBorderLeft(BorderStyle.THIN);
contentStyle.setBorderRight(BorderStyle.THIN);
contentStyle.setBorderTop(BorderStyle.THIN);
// 设置边框颜色
contentStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
contentStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
contentStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
contentStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());
// 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
return new HorizontalCellStyleStrategy(headWriteCellStyle, contentStyle);
}