标签:web list EasyExcel excel add new List response
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);
启动项目,访问即可下载。
标签:web,list,EasyExcel,excel,add,new,List,response 来源: https://www.cnblogs.com/charler/p/16616546.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。