最近项目上有excel导入、导出的需求,基于阿里巴巴开源的easyExcel做了一个简单的封装,希望能给大家带来一定的帮助,如果有问题请留言评论区。
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.0.1</version>
</dependency>
工具类
博主是在springBoot项目中使用的此工具类,所以如果使用@Autowired导入此工具类的话,请注意在此工具类上加上@Compoent注解 将bean注入容器管理
/**
* @param <T>
* @param <K>
* @author yuanChen
* @Date 2022-10-10
* @Description 基于阿里巴巴easyExcel实现,实现基础常用功能,可根据需求参考文档进行优化
* 功能:1.excel生成至本地 2.返回流供前端下载 3.读取本地excel文件 4.读取前端上传
* excel文件
* 参考文档https://easyexcel.opensource.alibaba.com/
* 注意文件路径在windows下,“/”,“\”都可以识别,unix只识别“/”,所以路径的拼接,更推荐使用File.separator
* 如:/excel/sampleData.xlsx 推荐使用 String path = File.separator + "excel" + File.separator + "sampleData.xlsx";
*/
@Component
public class ExcelUtils<T, K> {
/**
* 导出excel文件至浏览器下载
*
* @param list list格式的数据源,模板中使用{.}
* @param map map格式的数据源,模板中使用{},与list相比少了.
* @param response 相应浏览器的请求
* @param formWorkPathName 模板文件的路径 相对于resource文件夹,/excel/sampleData.xlsx,resource文件下excel文件夹下的sampleData文件
* @param outPutFileName 输出的文件名
*/
public void exportExcelToBrowser(T list, K map, HttpServletResponse response, String formWorkPathName, String outPutFileName) {
//模板文件编译后的位置
InputStream path = this.getClass().getResourceAsStream(formWorkPathName);
String filename = null;
try {
// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
filename = URLEncoder.encode(outPutFileName + System.currentTimeMillis(), "utf-8");
//ExcelWriter excelWriter = EasyExcel.write(filename).withTemplate(templateFileName).build();
WriteSheet writeSheet = EasyExcel.writerSheet()
.build();
//使用response.getOutputStream()下载,并使用项目下的模板填充
ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream())
.withTemplate(path)
.build();
//数据源,此处使用的方法为easyExcel的模板填充功能,与write不一样
if (map != null)