1. 程式人生 > >Spring Boot 入門(十二):報表匯出,對比poi、jxl和esayExcel的效率

Spring Boot 入門(十二):報表匯出,對比poi、jxl和esayExcel的效率

本片部落格是緊接著Spring Boot 入門(十一):整合 WebSocket, 實時顯示系統日誌寫的

關於poi、jxl和esayExcel的介紹自行百度。

  • jxl最多支援03版excel,所以單個sheet頁面最多隻能匯出65536條資料。
  • 我直接將excel匯入到瀏覽器並開啟,以下統計匯出時長指將資料從資料庫查詢,並寫入到excel的過程。不包括開啟excel所消耗的時間
  • 為了接近真實場景,我建了一個表,一共有32個欄位,其中2個id:一個自增長、一個UUID,10個int型欄位,10個String欄位,10個datatime欄位;匯出的excel包含了32個欄位
  • 我每次匯出一個excel後,直接將jvm的記憶體清空,再進行下一個excel的匯出,保證匯出excel不受其它執行緒的影響
  • 我只是為了比較效能,所以沒有對excel的樣式進行過多的渲染
  • poi方式,我使用的是重新整理硬碟的方式,資料量大於設定的值,就將記憶體中的資料重新整理到硬碟,降低OOM的概率,同時也增加了匯出效率

1.pom依賴

以下是poi、jxl和esayExcel的全部依賴

 1  <!--begin poi-->
 2         <dependency>
 3             <groupId>org.apache.poi</groupId>
 4             <artifactId>poi</artifactId>
 5             <version>${poi.version}</version>
 6         </dependency>
 7 
 8         <dependency>
 9             <groupId>org.apache.poi</groupId>
10             <artifactId>poi-ooxml</artifactId>
11             <version>${poi.version}</version>
12         </dependency>
13         <!--end poi-->
14         <!--begin jxl-->
15         <dependency>
16             <groupId>net.sourceforge.jexcelapi</groupId>
17             <artifactId>jxl</artifactId>
18             <version>2.6.10</version>
19         </dependency>
20         <!--end jxl-->
21         <!--begin esayExcel-->
22         <dependency>
23             <groupId>com.alibaba</groupId>
24             <artifactId>easyexcel</artifactId>
25             <version>1.1.2-beat1</version>
26         </dependency>
27         <!--end esayExcel-->

2.頁面

由於是直接將excel通過response相應的方式寫入到記憶體,然後在瀏覽器端開啟,所以頁面部分不能用ajax請求

1 <form class="form-horizontal">
2             <div class="form-group clearfix">
3                 <button type="button" onclick="report_poi();" class="btn btn-sm btn-warning">poi匯出</button>
4                 <button type="button" onclick="report_jxl();" class="btn btn-sm btn-danger">jxl匯出</button>
5                 <button type="button" onclick="report_esay_excel();" class="btn btn-sm btn-primary">esayExcel匯出</button>
6             </div>
7         </form>
 1  function report_poi() {
 2         window.location.href = "/conf/report/reportPoi";
 3     }
 4 
 5     function report_jxl() {
 6         window.location.href = "/conf/report/reportJxl";
 7     }
 8 
 9     function report_esay_excel() {
10         window.location.href = "/conf/report/reportEsayExcel";
11     }

3.後臺

在類中定義了一個常量,表示excel的表頭

1  // 報表的title
2     private static final String[] title = {"id", "報表id"
3             , "col1", "col2", "col3", "col4", "col5", "col6", "col7", "col8", "col9", "col10"
4             , "col11", "col12", "col13", "col14", "col15", "col16", "col17", "col18", "col19", "col20"
5             , "col21", "col22", "col23", "col24", "col25", "col26", "col27", "col28", "col29", "col30"};

 

(1)poi相關的後臺程式碼

 1  @Log("poi匯出報表")
 2     @RequestMapping(value = "/reportPoi", method = RequestMethod.GET)
 3     @ResponseBody
 4     public String reportPoi(HttpServletResponse response) throws Exception {
 5         //excel檔名
 6         log.info("poi方式開始匯出資料");
 7         response.reset();// 清空輸出流
 8         response.setHeader("Content-Disposition", "attachment;filename=poi.xlsx");
 9         response.setContentType("application/octet-stream;charset=UTF-8");
10         response.addHeader("Pargam", "no-cache");
11         response.addHeader("Cache-Control", "no-cache");
12         //sheet頁中的行數,行數資料;
13         List<Report> list = reportService.getAllDate();
14         long start = System.currentTimeMillis();
15         // 開始匯出excel
16         SXSSFWorkbook wb = new SXSSFWorkbook(1000);
17         SXSSFSheet sheet = wb.createSheet("poi");
18         CellStyle style = wb.createCellStyle();
19         style.setWrapText(true);
20         Row row = sheet.createRow(0);
21         Cell cell = null;
22         for (int i = 0; i < title.length; i++) {
23             cell = row.createCell(i);
24             cell.setCellValue(title[i]);
25             cell.setCellStyle(style);
26         }
27         for (int i = 0; i < list.size(); i++) {
28             Report report = list.get(i);
29             row = sheet.createRow(i + 1);
30             row.createCell(0).setCellValue(report.getId());
31             row.createCell(1).setCellValue(report.getReportId());
32             row.createCell(2).setCellValue(report.getCol1());
33             row.createCell(3).setCellValue(report.getCol2());
34             row.createCell(4).setCellValue(report.getCol3());
35             row.createCell(5).setCellValue(report.getCol4());
36             row.createCell(6).setCellValue(report.getCol5());
37             row.createCell(7).setCellValue(report.getCol6());
38             row.createCell(8).setCellValue(report.getCol7());
39             row.createCell(9).setCellValue(report.getCol8());
40             row.createCell(10).setCellValue(report.getCol9());
41             row.createCell(11).setCellValue(report.getCol10());
42             row.createCell(12).setCellValue(report.getCol11());
43             row.createCell(13).setCellValue(report.getCol12());
44             row.createCell(14).setCellValue(report.getCol13());
45             row.createCell(15).setCellValue(report.getCol14());
46             row.createCell(16).setCellValue(report.getCol15());
47             row.createCell(17).setCellValue(report.getCol16());
48             row.createCell(18).setCellValue(report.getCol17());
49             row.createCell(19).setCellValue(report.getCol18());
50             row.createCell(20).setCellValue(report.getCol19());
51             row.createCell(21).setCellValue(report.getCol20());
52             row.createCell(22).setCellValue(report.getCol21());
53             row.createCell(23).setCellValue(report.getCol22());
54             row.createCell(24).setCellValue(report.getCol23());
55             row.createCell(25).setCellValue(report.getCol24());
56             row.createCell(26).setCellValue(report.getCol25());
57             row.createCell(27).setCellValue(report.getCol26());
58             row.createCell(28).setCellValue(report.getCol27());
59             row.createCell(29).setCellValue(report.getCol28());
60             row.createCell(30).setCellValue(report.getCol29());
61             row.createCell(31).setCellValue(report.getCol30());
62 
63         }
64         long millis = System.currentTimeMillis() - start;
65         OutputStream os = response.getOutputStream();
66         wb.write(os);
67         os.flush();
68         os.close();
69         wb.dispose();
70         log.info("POI匯出報表,資料量:{},時間:{}ms", list.size(), millis);
71         return "";
72     }

(2)jxl相關後臺程式碼

 1 @Log("jxl匯出報表")
 2     @RequestMapping(value = "/reportJxl")
 3     @ResponseBody
 4     public String reportJxl(HttpServletResponse response) throws Exception {
 5         log.info("jxl方式開始匯出資料");
 6         try {
 7             long start = System.currentTimeMillis();
 8             OutputStream os = response.getOutputStream();// 取得輸出流
 9             response.reset();// 清空輸出流
10             response.setHeader("Content-disposition", "attachment; filename=" + java.net.URLEncoder.encode("jxl", "UTF-8") + "Excel.xlsx");// 設定輸出檔案頭
11             response.setContentType("application/msexcel");// 定義輸出型別
12             WritableWorkbook workbook = jxl.Workbook.createWorkbook(os); // 建立excel檔案
13             WritableSheet sheet1 = workbook.createSheet("jxl", 0);//第一個sheet名
14             // 通過函式WritableFont()設定字型樣式
15             // 第一個引數表示所選字型
16             // 第二個引數表示字型大小
17             // 第三個引數表示粗體樣式,有BOLD和NORMAL兩種樣式
18             // 第四個引數表示是否斜體
19             // 第五個引數表示下劃線樣式
20             // 第六個引數表示顏色樣式
21             WritableFont wf = new WritableFont(WritableFont.TIMES, 16, WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
22             CellFormat cf = new WritableCellFormat(wf);
23             // 設定表頭
24             for (int i = 0; i < title.length; i++) {
25                 sheet1.addCell(new Label(i, 0, title[i], cf));
26             }
27             List<Report> list = reportService.getAllDate();
28             //根據內容自動設定列寬(內容為英文時)
29             // 生成主體內容
30             for (int i = 0; i < list.size(); i++) {
31                 Report report = list.get(i);
32                 sheet1.addCell(new Label(0, i + 1, report.getId().toString()));
33                 sheet1.addCell(new Label(1, i + 1, report.getReportId()));
34                 sheet1.addCell(new Label(2, i + 1, report.getCol1().toString()));
35                 sheet1.addCell(new Label(3, i + 1, report.getCol2().toString()));
36                 sheet1.addCell(new Label(4, i + 1, report.getCol3().toString()));
37                 sheet1.addCell(new Label(5, i + 1, report.getCol4().toString()));
38                 sheet1.addCell(new Label(6, i + 1, report.getCol5().toString()));
39                 sheet1.addCell(new Label(7, i + 1, report.getCol6().toString()));
40                 sheet1.addCell(new Label(8, i + 1, report.getCol7().toString()));
41                 sheet1.addCell(new Label(9, i + 1, report.getCol8().toString()));
42                 sheet1.addCell(new Label(10, i + 1, report.getCol9().toString()));
43                 sheet1.addCell(new Label(11, i + 1, report.getCol10().toString()));
44                 sheet1.addCell(new Label(12, i + 1, report.getCol11()));
45                 sheet1.addCell(new Label(13, i + 1, report.getCol12()));
46                 sheet1.addCell(new Label(14, i + 1, report.getCol13()));
47                 sheet1.addCell(new Label(15, i + 1, report.getCol14()));
48                 sheet1.addCell(new Label(16, i + 1, report.getCol15()));
49                 sheet1.addCell(new Label(17, i + 1, report.getCol16()));
50                 sheet1.addCell(new Label(18, i + 1, report.getCol17()));
51                 sheet1.addCell(new Label(19, i + 1, report.getCol18()));
52                 sheet1.addCell(new Label(20, i + 1, report.getCol19()));
53                 sheet1.addCell(new Label(21, i + 1, report.getCol20()));
54                 sheet1.addCell(new Label(22, i + 1, report.getCol21().toString()));
55                 sheet1.addCell(new Label(23, i + 1, report.getCol22().toString()));
56                 sheet1.addCell(new Label(24, i + 1, report.getCol23().toString()));
57                 sheet1.addCell(new Label(25, i + 1, report.getCol24().toString()));
58                 sheet1.addCell(new Label(26, i + 1, report.getCol25().toString()));
59                 sheet1.addCell(new Label(27, i + 1, report.getCol26().toString()));
60                 sheet1.addCell(new Label(28, i + 1, report.getCol27().toString()));
61                 sheet1.addCell(new Label(29, i + 1, report.getCol28().toString()));
62                 sheet1.addCell(new Label(30, i + 1, report.getCol29().toString()));
63                 sheet1.addCell(new Label(31, i + 1, report.getCol30().toString()));
64             }
65             workbook.write(); // 寫入檔案
66             workbook.close();
67             os.close(); // 關閉流
68             long millis = System.currentTimeMillis() - start;
69             log.info("jxl匯出報表,資料量:{},時間:{}ms", list.size(), millis);
70         } catch (Exception e) {
71             log.error("jxl匯出報表報錯", e);
72         }
73         return "";
74     }

(3)esayExcel相關後臺程式碼

 1 @Log("esayExcel匯出報表")
 2     @RequestMapping(value = "/reportEsayExcel")
 3     @ResponseBody
 4     public String reportEsayExcel(HttpServletResponse response) throws Exception {
 5         log.info("esayExcel方式開始匯出資料");
 6         long start = System.currentTimeMillis();
 7 
 8         try {
 9             ExcelWriter writer = null;
10             OutputStream outputStream = response.getOutputStream();
11             //新增響應頭資訊
12             response.setHeader("Content-disposition", "attachment; filename= esayExcel.xlsx");
13             response.setContentType("application/msexcel;charset=UTF-8");//設定型別
14             response.setHeader("Pragma", "No-cache");//設定頭
15             response.setHeader("Cache-Control", "no-cache");//設定頭
16             response.setDateHeader("Expires", 0);//設定日期頭
17 
18             //例項化 ExcelWriter
19             writer = new ExcelWriter(outputStream, ExcelTypeEnum.XLSX, true);
20 
21             //例項化表單
22             Sheet sheet = new Sheet(1, 0, Report.class);
23             sheet.setSheetName("esayExcel");
24 
25             //獲取資料
26             List<Report> list = reportService.getAllDate();
27 
28             //輸出
29             writer.write(list, sheet);
30             writer.finish();
31             outputStream.flush();
32             long millis = System.currentTimeMillis() - start;
33             log.info("sayExcel匯出報表,資料量:{},時間:{}ms", list.size(), millis);
34         } catch (IOException e) {
35             log.error("esayExcel匯出excel報錯", e);
36         } finally {
37             try {
38                 response.getOutputStream().close();
39             } catch (IOException e) {
40                 log.error("esayExcel關閉資源", e);
41             }
42         }
43         return "";
44     }
 1 package com.learn.hello.system.common.listener;
 2 
 3 import com.alibaba.excel.context.AnalysisContext;
 4 import com.alibaba.excel.event.AnalysisEventListener;
 5 import lombok.extern.slf4j.Slf4j;
 6 import org.apache.poi.ss.formula.functions.T;
 7 
 8 import java.util.ArrayList;
 9 import java.util.List;
10 
11 /**
12  * @ClassName ExcelListener
13  * @Deccription 通過esayExcel的方式匯出excel
14  * @Author DZ
15  * @Date 2020/1/20 22:28
16  **/
17 @Slf4j
18 public class ExcelListener extends AnalysisEventListener<T> {
19     //可以通過例項獲取該值
20     private final List<T> rows = new ArrayList<>();
21 
22     @Override
23     public void invoke(T object, AnalysisContext analysisContext) {
24         //資料儲存到list,供批量處理,或後續自己業務邏輯處理。
25         rows.add(object);
26     }
27 
28     @Override
29     public void doAfterAllAnalysed(AnalysisContext analysisContext) {
30     }
31 
32     public List<T> getRows() {
33         return rows;
34     }
35 }
ExcelListener 這個類中還可以做很多工作,比喻在doAfterAllAnalysed中做一些銷燬工作,日誌記錄等。在invoke中做一些業務相關的工作,或者對rows進行遍歷處理

實體類:
  1 package com.learn.hello.modules.entity;
  2 
  3 import com.alibaba.excel.annotation.ExcelProperty;
  4 import com.alibaba.excel.metadata.BaseRowModel;
  5 import lombok.Data;
  6 
  7 import javax.persistence.*;
  8 import java.util.Date;
  9 
 10 @Data
 11 @Table(name = "t_report")
 12 public class Report extends BaseRowModel {
 13     @ExcelProperty(value = "id", index = 0)
 14     @Id
 15     @GeneratedValue(strategy = GenerationType.IDENTITY)
 16     private Integer id;
 17 
 18     /**
 19      * 報表id
 20      */
 21     @ExcelProperty(value = "報表id", index = 1)
 22     @Column(name = "report_id")
 23     private String reportId;
 24 
 25     @ExcelProperty(value = "col1", index = 2)
 26     private Integer col1;
 27 
 28     @ExcelProperty(value = "col2", index = 3)
 29     private Integer col2;
 30 
 31     @ExcelProperty(value = "col3", index = 4)
 32     private Integer col3;
 33 
 34     @ExcelProperty(value = "col4", index = 5)
 35     private Integer col4;
 36 
 37     @ExcelProperty(value = "col5", index = 6)
 38     private Integer col5;
 39 
 40     @ExcelProperty(value = "col6", index = 7)
 41     private Integer col6;
 42 
 43     @ExcelProperty(value = "col7", index = 8)
 44     private Integer col7;
 45 
 46     @ExcelProperty(value = "col8", index = 9)
 47     private Integer col8;
 48 
 49     @ExcelProperty(value = "col9", index = 10)
 50     private Integer col9;
 51 
 52     @ExcelProperty(value = "col10", index = 11)
 53     private Integer col10;
 54 
 55     @ExcelProperty(value = "col11", index = 12)
 56     private String col11;
 57 
 58     @ExcelProperty(value = "col12", index = 13)
 59     private String col12;
 60 
 61     @ExcelProperty(value = "col13", index = 14)
 62     private String col13;
 63 
 64     @ExcelProperty(value = "col14", index = 15)
 65     private String col14;
 66 
 67     @ExcelProperty(value = "col15", index = 16)
 68     private String col15;
 69 
 70     @ExcelProperty(value = "col16", index = 17)
 71     private String col16;
 72 
 73     @ExcelProperty(value = "col17", index = 18)
 74     private String col17;
 75 
 76     @ExcelProperty(value = "col18", index = 19)
 77     private String col18;
 78 
 79     @ExcelProperty(value = "col19", index = 20)
 80     private String col19;
 81 
 82     @ExcelProperty(value = "col20", index = 21)
 83     private String col20;
 84 
 85     @ExcelProperty(value = "col21", index = 22)
 86     private Date col21;
 87 
 88     @ExcelProperty(value = "col22", index = 23)
 89     private Date col22;
 90 
 91     @ExcelProperty(value = "col23", index = 24)
 92     private Date col23;
 93 
 94     @ExcelProperty(value = "col24", index = 25)
 95     private Date col24;
 96 
 97     @ExcelProperty(value = "col25", index = 26)
 98     private Date col25;
 99 
100     @ExcelProperty(value = "col26", index = 27)
101     private Date col26;
102 
103     @ExcelProperty(value = "col27", index = 28)
104     private Date col27;
105 
106     @ExcelProperty(value = "col28", index = 29)
107     private Date col28;
108 
109     @ExcelProperty(value = "col29", index = 30)
110     private Date col29;
111 
112     @ExcelProperty(value = "col30", index = 31)
113     private Date col30;
114 
115 }

其中@ExcelProperty(value = "col30", index = 14)註解是給esayExcel'使用的,poi和jxl使用這個實體的時候,這行註解可以忽略

 

4.效能比較

以下是列印的日誌:由於jxl最多隻能匯出65536條資料,所以在70W條資料匯出的時候,就沒有jxl的相關耗時。此外,在匯出第80W條以及以後的資料的時候,我將jvm記憶體清空了,讓jvm以最佳的狀態匯出,所以60W到80W的時候,耗時並沒有增加多少

**************************************************idea打印出的日誌************************************************

POI匯出報表,資料量:10001,時間:752ms
jxl匯出報表,資料量:10001,時間:993ms
sayExcel匯出報表,資料量:10001,時間:2189ms

POI匯出報表,資料量:20001,時間:1527ms
jxl匯出報表,資料量:20001,時間:2447ms
sayExcel匯出報表,資料量:20001,時間:3481ms

POI匯出報表,資料量:30001,時間:1538ms
jxl匯出報表,資料量:30001,時間:2520ms
sayExcel匯出報表,資料量:30001,時間:5102ms

POI匯出報表,資料量:40001,時間:1892ms
jxl匯出報表,資料量:40001,時間:3549ms
sayExcel匯出報表,資料量:40001,時間:7523ms

POI匯出報表,資料量:50001,時間:2395ms
jxl匯出報表,資料量:50001,時間:4714ms
sayExcel匯出報表,資料量:50001,時間:8319ms

POI匯出報表,資料量:60001,時間:2860ms
jxl匯出報表,資料量:60001,時間:5255ms
sayExcel匯出報表,資料量:60001,時間:10197ms

POI匯出報表,資料量:70001,時間:3693ms
sayExcel匯出報表,資料量:70001,時間:11595ms

POI匯出報表,資料量:80001,時間:3843ms
sayExcel匯出報表,資料量:80001,時間:13928ms

POI匯出報表,資料量:90001,時間:4319ms
sayExcel匯出報表,資料量:90001,時間:14901ms

POI匯出報表,資料量:100001,時間:4943ms
sayExcel匯出報表,資料量:100001,時間:15962ms

POI匯出報表,資料量:200011,時間:11296ms
sayExcel匯出報表,資料量:200011,時間:33037ms

POI匯出報表,資料量:300011,時間:14947ms
sayExcel匯出報表,資料量:300011,時間:49748ms

POI匯出報表,資料量:400011,時間:19626ms
sayExcel匯出報表,資料量:400011,時間:66043ms

POI匯出報表,資料量:600011,時間:34418ms
sayExcel匯出報表,資料量:600011,時間:101819ms


POI匯出報表,資料量:800011,時間:38726ms
sayExcel匯出報表,資料量:800011,時間:135209ms

POI匯出報表,資料量:1000011,時間:47433ms
sayExcel匯出報表,資料量:1000011,時間:167676ms

**************************************************idea打印出的日誌************************************************

 

對上面的資料量取整,統計圖如下:

 

 

 第一行為資料量,從3W到100W

 第二到四行為匯出excel消耗的時間,單位為毫秒

 

 

 其中縱座標為匯出時間,橫軸為匯出數量。

結論:

  • 從時間上:poi>jxl>esayExcel
  • 從程式碼簡潔程度上:esayExce>jxl>poi
  • 從jvm記憶體消耗上,我監控的是最高峰的記憶體消耗量:3中方式都差不多(網上說esayExcel消耗記憶體很小,我真的沒看出來)
  • jxl可以直接設定excel模板,所以對於複雜表頭的excel,jxl處理起來很方便(具體可以自行搜尋jxl 模板 匯出)
  • esayExcel目前沒有提供較複雜的api,無法匯出較複雜的資料(二進位制圖片,音樂等)

如果對於表頭簡單,且資料量小於10W條資料的,推薦使用esayExcel該方式程式碼很簡潔,10W以下的匯出效率還行

如果小於60W條資料,表頭複雜建議使用jxl;表頭簡單,建立使用poi

如果大於60W條資料,選擇poi

poi方式處理程式碼繁瑣點,效能很好,不知道如何選擇,就直接使用poi,不會出錯

完整的專案和程式碼見:https://gitee.com/bald_dz/Springboot