
今天想写一个双层表头的excel导出,一开始使用的是poi来画发现太麻烦, 于是就想到了使用easy-excel的模板填充来实现,将导出写成了一个简单的工具类, 供参考
最终是要实现为这样的一个效果 , 红色为表头,绿色为表体,于是我先做出了一个模板 ,
如果不会写模板的可以去看官方文档, 十分简单 https://www.yuque.com/easyexcel/doc/fill
然后将表头数据封装成一个map,表体数据为一个list , 去调用工具类就实现了
以下为工具类代码,导入了easy-excel就可以使用
package com.org.inventory.util;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import org.springframework.core.io.ClassPathResource;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
public class EasyExcelUtils {
private static final String CONTENT_TYPE = "application/vnd.ms-excel";
private static final String CHARACTER_ENCODING = "utf-8";
private static final String HEADER_S1 = "Content-disposition";
private static final String HEADER_S2 = "attachment; filename=";
public static void createExcel(HttpServletResponse response, String fileName, Map map, List> list) throws IOException {
// 设置公共头信息
OutputStream out = null;
BufferedOutputStream bos = null;
response.setContentType(CONTENT_TYPE);
response.setCharacterEncoding(CHARACTER_ENCODING);
response.setHeader(HEADER_S1, HEADER_S2 + fileName);
out = response.getOutputStream();
bos = new BufferedOutputStream(out);
// 此处可以修改 为 classpath:/file
ClassPathResource cpr = new ClassPathResource("file" + File.separator + fileName);
ExcelWriter excelWriter = com.alibaba.excel.EasyExcel.write(bos)
.withTemplate(cpr.getInputStream()).excelType(ExcelTypeEnum.XLS).build();
WriteSheet writeSheet = com.alibaba.excel.EasyExcel.writerSheet().build();
FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
// 填充 list 数据
excelWriter.fill(list, fillConfig, writeSheet);
// 填充 map 数据
excelWriter.fill(map, writeSheet);
excelWriter.finish();
bos.flush();
bos.close();
}
}
直接调用即可
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)