一、需求描述
用户点击导出,需要将某些信息导出成excel文件
二、需求实现
首先导入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.1.1</version>
</dependency>
2.1、简单格式导出
对于格式要求比较简单的excel表格,可以直接代码生成
- 代码示例
@GetMapping("/test")
public void test(HttpServletResponse res) throws IOException {
// 表头
List<String> headList = Lists.newArrayList("id", "name", "age");
List<List<String>> headColList = Lists.newArrayList();
headList.forEach(head -> {
List<String> headCol = Lists.newArrayList(head);
headColList.add(headCol);
});
// 数据
List<List<Object>> dataList = new ArrayList<>();
List<Object> data = new ArrayList<>();
data.add("1");
data.add("lisi");
data.add("12");
dataList.add(data);
// 导出的excel文件信息
String fileName = "test.xlsx";
res.setContentType("application/vnd.ms-excel");
res.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + fileName);
// 导出
ClassPathResource resource = new ClassPathResource("template/data.xlsx");
EasyExcel.write(res.getOutputStream()).head(headColList).sheet().doWrite(dataList);
}
2.2、复杂格式导出
对于格式比较复杂的表格,我们可以提前设置好模板,往里面填充数据即可
// 只需读取模板文件,然后传入withTemplate方法即可
ClassPathResource resource = new ClassPathResource("template/data.xlsx");
EasyExcel.write(res.getOutputStream()).withTemplate(resource.getInputStream()).head(headColList).sheet().doWrite(dataList);
最后修改时间:2024-07-03 20:08:32
「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。





