使用EasyExcel实现web的excel下载
2022/8/23 23:22:46
本文主要是介绍使用EasyExcel实现web的excel下载,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
Excel 下载算是比较基础常见的需求了,一般有两种实现,一种使用Poi,第二种就是本文的EasyExcel实现下载,与前者相对比,EasyExcel做了进一步的封装,更容易实现了,贴上EasyExcel的官方文档:https://easyexcel.opensource.alibaba.com/
1、引入依赖
1 <dependency> 2 <groupId>com.alibaba</groupId> 3 <artifactId>easyexcel</artifactId> 4 <version>2.2.6</version> 5 </dependency> 6 <dependency> 7 <groupId>org.apache.poi</groupId> 8 <artifactId>poi</artifactId> 9 <version>3.17</version> 10 </dependency> 11 <dependency> 12 <groupId>org.apache.poi</groupId> 13 <artifactId>poi-ooxml</artifactId> 14 <version>3.17</version>
第一个依赖就是easyexcel的主要依赖,后面两个则为解决easy可能报错所需要引入的依赖
2、实现需要被写入excel对应的bean
1 @Data 2 public class DownloadData { 3 @ExcelProperty 4 private String string; 5 @ExcelProperty 6 private Date date; 7 @ExcelProperty 8 @ContentStyle(dataFormat = 2) 9 private Double doubleData; 10 }
这个bean需要与生成的excel的列一致,不一致可以使用 @ExcelIgnoreUnannotated 注释忽略所选属性
出处:https://github.com/alibaba/easyexcel/issues/1799#top
3、构建List<Bean>
将需要写入的数据构建为List<Bean> 的结构,在例子中,则是为List<DownloadData>
1 @RestController 2 public class ExcelDownloadController { 3 @GetMapping("/download") 4 public void download(HttpServletResponse response) throws IOException { 5 response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); 6 response.setCharacterEncoding("UTF-8"); 7 String fileName = URLEncoder.encode("下载功能测试", "UTF-8"). 8 replaceAll("\\+", "%20"); 9 List<DownloadData> list = new ArrayList<>(); 10 list.add(new DownloadData("1",new Date(),3.213)); 11 list.add(new DownloadData("1",new Date(),3.213)); 12 list.add(new DownloadData("1",new Date(),3.213)); 13 List<String> header = new ArrayList<>(); 14 header.add("value1"); 15 header.add("value2"); 16 header.add("value3"); 17 response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); 18 response.setCharacterEncoding("utf-8"); 19 // 防止中文乱码 20 response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx"); 21 EasyExcel.write(response.getOutputStream(), DownloadData.class).sheet("模板").doWrite(list);
启动项目,访问即可下载。
这篇关于使用EasyExcel实现web的excel下载的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15PingCAP 黄东旭参与 CCF 秀湖会议,共探开源教育未来
- 2024-05-13PingCAP 戴涛:构建面向未来的金融核心系统
- 2024-05-09flutter3.x_macos桌面os实战
- 2024-05-09Rust中的并发性:Sync 和 Send Traits
- 2024-05-08使用Ollama和OpenWebUI在CPU上玩转Meta Llama3-8B
- 2024-05-08完工标准(DoD)与验收条件(AC)究竟有什么不同?
- 2024-05-084万 star 的 NocoDB 在 sealos 上一键起,轻松把数据库编程智能表格
- 2024-05-08Mac 版Stable Diffusion WebUI的安装
- 2024-05-08解锁CodeGeeX智能问答中3项独有的隐藏技能
- 2024-05-08RAG算法优化+新增代码仓库支持,CodeGeeX的@repo功能效果提升