依赖
<!-- https://mvnrepository.com/artifact/com.alibaba/easyexcel -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.0.5</version>
</dependency>
实体类
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;
@Data
public class DictEeVo {
@ExcelProperty(value = {"第一级","用户", "id"}, index = 0)
private Long id = 1L;
@ExcelProperty(value = {"第一级","用户", "上级id"}, index = 1)
private Long parentId = 2L;
@ExcelProperty(value = {"第二级","用户", "名称"}, index = 2)
private String name = "名称";
@ExcelProperty(value = {"第三级","数据", "值"}, index = 3)
private String value = "值";
@ExcelProperty(value = {"第三级","数据", "编码"}, index = 4)
private String dictCode = "编码";
}
controller
@Controller
public class Controlller {
@GetMapping("download")
public void exportData(HttpServletResponse response) throws IOException {
//设置文件的响应类型
response.setContentType("application/vnd.ms-excel");
//设置响应编码
response.setCharacterEncoding("utf-8");
//设置文件名的编码格式,防止文件名乱码
String fileName = URLEncoder.encode("数据字典", "UTF-8");
//固定写法,设置响应头
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
//查询信息
ArrayList<DictEeVo> dictEeVos = new ArrayList<>();
for (int i = 0; i < 20; i++) {
dictEeVos.add(new DictEeVo());
}
//进行写操作,用过响应流对象响应,该出也可改为具体的文件路径进行写出文件到指定路径下
EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("数据字典").doWrite(dictEeVos);
}
}
参考文章
https://blog.csdn.net/qq_39084191/article/details/122842113
实体类
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;
@Data
public class DictEeVo {
@ExcelProperty(value = {"第一级","用户", "id"}, index = 0)
private Long id = 1L;
@ExcelProperty(value = {"第一级","用户", "上级id"}, index = 1)
private Long parentId = 2L;
@ExcelProperty(value = {"第二级","用户", "名称"}, index = 2)
private String name = "名称";
@ExcelProperty(value = {"数据", "值"}, index = 3)
private String value = "值";
@ExcelProperty(value = {"数据", "编码"}, index = 4)
private String dictCode = "编码";
}
多sheet多表头填充
@GetMapping("download")
public void exportData(HttpServletResponse response) throws IOException {
//设置文件的响应类型
response.setContentType("application/vnd.ms-excel");
//设置响应编码
response.setCharacterEncoding("utf-8");
//设置文件名的编码格式,防止文件名乱码
String fileName = URLEncoder.encode("数据字典", "UTF-8");
//固定写法,设置响应头
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
//查询信息
ArrayList<DictEeVo> dictEeVos = new ArrayList<>();
for (int i = 0; i < 20; i++) {
dictEeVos.add(new DictEeVo());
}
ArrayList<DictEeVo> dictEeVos2 = new ArrayList<>();
for (int i = 0; i < 30; i++) {
dictEeVos2.add(new DictEeVo());
}
//进行写操作,用过响应流对象响应,该出也可改为具体的文件路径进行写出文件到指定路径下
// EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("数据字典"+dictEeVos.size()).doWrite(dictEeVos);
ExcelWriter build = EasyExcel.write(response.getOutputStream(), DictEeVo.class)
.build();
build.write(dictEeVos, EasyExcel.writerSheet(0).build());
build.write(dictEeVos2, EasyExcel.writerSheet(1).build());
build.finish();
}