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);
启动项目,访问即可下载。
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/281888.html