一、动态表头easyExcel导出。
上次用easyExcel做了个动态表头导入(https://blog.csdn.net/qq_37337660/article/details/110288393),不过,当时用的版本过低,并且也没有详细说明,这次整了个easyExcel动态表头的导出。
固定表头的有实体类,可以用注解,比较简单(下面参考罗列一些我觉得有用的处理办法),因为业务需要所以整动态表头(表头名称和数目都不固定)。还有经常出的错误
官网:https://www.yuque.com/easyexcel 有问题可以里面找解决办法。
1、加依赖
<!--easyExcel-->这个是必须,版本最新了。
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.7</version>
</dependency>
这个和第四个是升级了,支持某些功能和解决报错
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.0</version>
</dependency>
这个是解决乱七八糟报错当时
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.0</version>
</dependency>
2、自己搞了个工具类
package com.trs.ai.ty.utils;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import org.apache.poi.ss.usermodel.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
/**
* easyExcel工具类
*
* @author li.chengzhen
* @version 1.0
* @date 2021/3/2 16:34
*/
public class EasyExcelUtil {
/**
* 导出
*
* @param response HttpServletResponse
* @param headFiled 表头
* @param data 表数据
*/
public static void export(
HttpServletResponse response, List<List<String>> headFiled, List<List<Object>> data)
throws IOException {
EasyExcel.write(response.getOutputStream())
.head(headFiled)
// 样式
.registerWriteHandler(getHorizontalCellStyleStrategy())
.autoCloseStream(Boolean.FALSE)
.sheet(0)
.doWrite(data);
}
/**
* 设置请求头、文件名
*
* @param fileName excel文件名
*/
public static void setResponse(HttpServletResponse response, String fileName) {
// 编码设置成UTF-8,excel文件格式为.xlsx
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
// 这里URLEncoder.encode可以防止中文乱码 和easyexcel本身没有关系
fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8);
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
}
/**
* excel首列序号列样式
*
* @param workbook Workbook
* @return org.apache.poi.ss.usermodel.CellStyle
*/
public static CellStyle firstCellStyle(Workbook workbook) {
CellStyle cellStyle = workbook.createCellStyle();
// 居中
cellStyle.setAlignment(HorizontalAlignment.CENTER);
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cellStyle.setFillForegroundColor(IndexedColors.SKY_BLUE.

最低0.47元/天 解锁文章
821





