可以在代码里面自定义表头 也可以根据前端传入字段当表头 只需要封装到List headTitles = Lists.newArrayList();即可
easyExcel文档
/**
* 根据参数只导出指定列
*
* 1. 创建excel对应的实体对象 参照{@link DemoData}
*
* 2. 根据自己或者排除自己需要的列
*
* 3. 直接写即可
*
* @since 2.1.1
*/
@Test
public void excludeOrIncludeWrite() {
String fileName = TestFileUtil.getPath() + "excludeOrIncludeWrite" + System.currentTimeMillis() + ".xlsx";
// 这里需要注意 在使用ExcelProperty注解的使用,如果想不空列则需要加入order字段,而不是index,order会忽略空列,然后继续往后,而index,不会忽略空列,在第几列就是第几列。
// 根据用户传入字段 假设我们要忽略 date
Set<String> excludeColumnFiledNames = new HashSet<String>();
excludeColumnFiledNames.add("date");
// 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
EasyExcel.write(fileName, DemoData.class).excludeColumnFiledNames(excludeColumnFiledNames).sheet("模板")
.doWrite(data());
fileName = TestFileUtil.getPath() + "excludeOrIncludeWrite" + System.currentTimeMillis() + ".xlsx";
// 根据用户传入字段 假设我们只要导出 date
Set<String> includeColumnFiledNames = new HashSet<String>();
includeColumnFiledNames.add("date");
// 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
EasyExcel.write(fileName, DemoData.class).includeColumnFiledNames(includeColumnFiledNames).sheet("模板")
.doWrite(data());
}
封装成Util
package com.sangfor.utils;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.support.ExcelTypeEnum;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;
/**
* 对excel操作的工具类
* 可以根据自己用的类去生成
*
* @Author chenzhixiang
* @create 2021-09-12 00:23
*/
@Slf4j
public class EasyExcelUtil {
/**
* 读取excel
*
* @param file 导入的文件流
* @param model 生成的类
* @param
* @return 对象数组
*/
public static <T> List<T> readExcel(InputStream file, Class<T> model) {
List<T> list = new ArrayList<>();
EasyExcel
//读取的文件
.read(file)
//反射获取类型
.head(model)
//excel类型
.excelType(ExcelTypeEnum.XLSX)
//读取的excel左下角的名字
.sheet(0)
//从第二行开始读
.headRowNumber(2)
//注册监听器
.registerReadListener(new AnalysisEventListener<T>() {
@Override
public void invoke(T t, AnalysisContext analysisContext) {
list.add(t);
}
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
System.out.println("读取完毕" + model);
}
}).doRead();
return list;
}
/**
* 响应给浏览器的excel文件
*
* @param response servlet响应对象
* @param fileName 设置文件明
* @param list 数据列表
* @param clazz 响应类
* @param
* @throws IOException
*/
public static <T> void writerExcel(HttpServletResponse response, String fileName, List<T> list, Class<T> clazz) {
try {
// response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("UTF-8");
// 这里URLEncoder.encode可以防止中文乱码 当然和easyExcel没有关系
String encode = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + encode + ".xlsx");
EasyExcel.write(response.getOutputStream(), clazz)
//设置不自动关闭流
.autoCloseStream(Boolean.FALSE)
// .registerWriteHandler(new ExcelSheetWriteHandler())
.sheet(fileName)
.doWrite(list);
} catch (Exception e) {
//重置response
response.reset();
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
Map<String, String> map = new HashMap<String, String>();
map.put("status", "failure");
map.put("message", "下载文件失败:" + e.getMessage());
System.out.println(e);
log.error("文件下载失败");
}
}
/**
* 自定义导出
*
* @param response servlet响应对象
* @param fileName 设置文件明
* @param list 数据列表
* @param clazz 响应类
* @param
* @throws IOException
*/
public static <T> void customizeWriterExcel(HttpServletResponse response, String fileName, List<T> list, Class<T> clazz, Set<String> includeColumnFiledNames) {
try {
// response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("UTF-8");
// 这里URLEncoder.encode可以防止中文乱码 当然和easyExcel没有关系
String encode = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + encode + ".xlsx");
EasyExcel.write(response.getOutputStream(), clazz)
//设置不自动关闭流
.autoCloseStream(Boolean.FALSE)
.includeColumnFiledNames(includeColumnFiledNames)
// .registerWriteHandler(new ExcelSheetWriteHandler())
.sheet(fileName)
.doWrite(list);
} catch (Exception e) {
//重置response
response.reset();
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
Map<String, String> map = new HashMap<String, String>();
map.put("status", "failure");
map.put("message", "下载文件失败:" + e.getMessage());
System.out.println(e);
log.error("文件下载失败");
}
}
/**
* 响应给浏览器的excel文件
*
* @param response servlet响应对象
* @param fileName 设置文件明
* @param list 数据列表
* @param
* @throws IOException
*/
public static <T> void writerExcelNew(HttpServletResponse response, String fileName, List<T> list) {
try {
response.setCharacterEncoding("UTF-8");
// 这里URLEncoder.encode可以防止中文乱码 当然和easyExcel没有关系
String encode = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + encode + ".xlsx");
EasyExcel.write(response.getOutputStream(), list.get(0).getClass())
//设置不自动关闭流
.autoCloseStream(Boolean.FALSE)
.sheet(fileName)
.doWrite(list);
} catch (Exception e) {
//重置response
response.reset();
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
HashMap<String, String> map = new HashMap<String, String>();
map.put("status", "failure");
map.put("message", "下载文件失败:" + e.getMessage());
log.error("文件下载失败");
}
}
public static void downloadExcel(HttpServletResponse response, InputStream input, String fileName) {
try {
OutputStream out = response.getOutputStream();
// 设置要下载的文件的名称
response.setHeader("Content-disposition", "attachment;fileName=" + fileName);
// 通知文件的MIME类型
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
byte[] b = new byte[2048];
int len;
while ((len = input.read(b)) != -1) {
out.write(b, 0, len);
}
input.close();
} catch (Exception e) {
log.error("文件下载失败");
}
}
}
@ApiOperation(value = "demo")
@PostMapping("/demo")
public void excel(HttpServletResponse response) throws IOException {
// 文件输出位置
//从response拿out 则是默认下载
OutputStream out = response.getOutputStream();
//固定位置下载路径
// OutputStream out = new FileOutputStream("d://test.xlsx");
//设置返回格式
response.addHeader("Content-Disposition", "attachment;filename=fileName" + ".xlsx");
ExcelWriter writer = EasyExcelFactory.write(out).build();
// 动态添加表头,适用一些表头动态变化的场景
WriteSheet sheet1 = new WriteSheet();
sheet1.setSheetName("商品明细");
sheet1.setSheetNo(0);
// 创建一个表格,用于 Sheet 中使用
WriteTable table = new WriteTable( );
table.setTableNo(1);
//表头数据
List<List<String>> headTitles = Lists.newArrayList();
//第一列,1/2/3行
headTitles.add(Lists.newArrayList( "交通"));
headTitles.add(Lists.newArrayList( "数量"));
headTitles.add(Lists.newArrayList( "商品"));
headTitles.add(Lists.newArrayList( "数字"));
headTitles.add(Lists.newArrayList( "等级"));
headTitles.add(Lists.newArrayList( "程度"));
//造数据
List<List<Object>> contentList = Lists.newArrayList();
contentList.add(Lists.newArrayList("骑车", "10", "苹果", "25", "2级", "40%"));
table.setHead(headTitles);
// 写数据
writer.write(contentList, sheet1, table);
writer.finish();
out.close();
}