轉自:http://www.dreamwu.com/post-425.html
今天的積累都是為了更好的明天,加油!我是java程序員可以關注我一起學習哈!
今天心血來潮,突然想起很久以前的一個導出excel的功能,以前用的poi感覺挺麻煩的!今天就簡單寫下EasyExcel版本的,EasyExcel是阿里的一個開源框架!github地址https://github.com/alibaba/easyexcel大家也可以下載下來看看源碼!我這里只做了一個簡單的demo!
EasyExcel和POI的對比
1、相比於POI,EasyExcel簡化了開發量,能夠用更少的代碼實現更多的功能
2、相比於POI,EasyExcel使用簡單
3、相比於POI,EasyExcel能夠使用更少的內存占用
首先我們創建一個springboot項目,在此就不過多的啰嗦,創建好之后,首先需要引入easyexcel的包!
引入依賴
<!--easyexcel--> <dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>1.1.2-beta5</version> </dependency>
實體類
@Data public class Users extends BaseRowModel { @ExcelProperty(value = {"主鍵ID"}, index = 0) private String id; @ExcelProperty(value = {"用戶姓名"}, index = 1) private String name; @ExcelProperty(value = {"用戶年齡"}, index = 2) private String age; }
Controller層
@RequestMapping("/exportExcel") public void export(HttpServletResponse response) throws IOException { List<Users> list = userService.findAllUser(); ServletOutputStream out = response.getOutputStream(); ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, true); String fileName = "測試exportExcel"; Sheet sheet = new Sheet(1, 0,Users.class); //設置自適應寬度 sheet.setAutoWidth(Boolean.TRUE); // 第一個 sheet 名稱 sheet.setSheetName("第一個sheet"); writer.write(list, sheet); //通知瀏覽器以附件的形式下載處理,設置返回頭要注意文件名有中文 response.setHeader("Content-disposition", "attachment;filename=" + new String( fileName.getBytes("gb2312"), "ISO8859-1" ) + ".xlsx"); writer.finish(); response.setContentType("multipart/form-data"); response.setCharacterEncoding("utf-8"); out.flush(); }
看下效果吧!
EasyExcel的確要比poi操作簡單的多!