Excel導出功能大多數用的都是 Apache POI 來進行Excel檔案的建立,為了美化導出的 Excel 檔案内容,通常會對單元格進行自适應資料長度的處理, Apache POI 提供了 autoColumnWidth(int column) 方法來自适應單元格長度,但我在使用的過程中發現了這個方法具有嚴重的性能問題,下面來看一個例子
使用程式建立50000個單元格進行性能測試
public static void main(String[] args){
HSSFWorkbook wb = new HSSFWorkbook();
int allTime = 0;
for(int s=1;s<=3;s++){
HSSFSheet sheet = wb.createSheet(s+"");
long time1 = new Date().getTime();
for (int i=0;i<50000;i++){
String str = "DemoLiuCSDNtest測試";
str+= Math.random();
HSSFRow row = sheet.createRow(i);
HSSFCell cell = row.createCell(0);
cell.setCellValue(str);
}
sheet.autoSizeColumn(0);
long time2 = new Date().getTime();
allTime += time2-time1;
System.out.println("第"+s+"次:"+(time2 - time1));
}
System.out.println("平均用了大約"+allTime/3+"毫秒");
}
運作結果:
第1次:9737
第2次:5878
第3次:6458
平均用了大約7357豪秒
可以看到,僅僅是50000個單元格,使用 autoColumnWidth(int column) 方法就占用了7秒的時間,并且這種設定不支援中文,這對使用者來說毫無體驗可言,
這是因為這個方法循環了sheet中的每一個單元格,感興趣的可以看看源碼,這裡不再貼出,下面給出一種解決方法
public static void main(String[] args){
HSSFWorkbook wb = new HSSFWorkbook();
int allTime = 0;
//建立集合存儲字段和最大長度 key:字段 value:單元格最大長度
Map<Integer,Integer> sizeMap = new HashMap<>();
sizeMap.put(0,0);
for(int s=1;s<=3;s++){
HSSFSheet sheet = wb.createSheet(s+"");
long time1 = new Date().getTime();
for (int i=0;i<50000;i++){
String str = "DemoLiuCSDNtest測試";
str+= Math.random();
HSSFRow row = sheet.createRow(i);
HSSFCell cell = row.createCell(0);
cell.setCellValue(str);
//篩選單元格最大長度
sizeMap.put(0,Math.max(sizeMap.get(0), str.getBytes().length));
}
//設定單元格長度, 這裡要乘上256
for (Integer i : sizeMap.keySet()) {
sheet.setColumnWidth(i,sizeMap.get(i)*256);
}
long time2 = new Date().getTime();
allTime += time2-time1;
System.out.println("第"+s+"次:"+(time2 - time1));
}
System.out.println("平均用了大約"+allTime/3+"豪秒");
}
運作結果:
第1次:412
第2次:141
第3次:692
平均用了大約415豪秒
可以看到,建立50000個單元格用時不到0.5秒,并且支援中文資料自适應單元格長度
另外,我寫了一個傳入List集合即可生成 HSSFWorkbook,導出Excel 的工具類,已上傳到GitHub
傳送門-->ExcelUtil.java