Author: Dorae
Date: 2018年10月23日12:30:15 轉載請註明出處git
最近接到了和Excel導出相關的需求,可是:github
若是數據量較小的話,這種方式並不會存在問題,可是當數據量比較大時,存在很是嚴重的問題:安全
OOM(由於數據並無被即便的寫入磁盤);架構
耗時(串行化);app
HSS對單sheet的數據量限制(65535),XSS爲100萬+。xss
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet(sheetName);
// 建立表頭
...
// 寫入數據
for (...) {
HSSFRow textRow = sheet.createRow(rowIndex);
for (...) {
HSSFCell textcell = textRow.createCell(colIndex);
textcell.setCellValue(value);
}
}
複製代碼
爲了改善上出方案的問題,SXSS採用了緩衝的方式,即按照某種策略按期刷盤。從而解決了OOM與耗時太長的問題。使用姿式:ide
InputStream inputStream = new FileInputStream(file);
XSSFWorkbook xssfWorkbook = new XSSFWorkbook(inputStream);
SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook(xssfWorkbook,properties.getRowAccessWindowsize());
Sheet sheet = sxssfWorkbook.getSheet(properties.getSheetName());
if (sheet == null) {
sheet = sxssfWorkbook.createSheet(properties.getSheetName());
}
// 建立表頭
...
// 寫入數據
for (...) {
Row row = sheet.createRow(row);
row.setValue(value);
}
FileOutputStream outputStream = new FileOutputStream(file);
sxssfWorkbook.write(outputStream);
複製代碼
雖然SXSS解決了OMM與耗時的問題,可是使用起來不太方便,會形成不少重複代碼,因而產生了EasyUtil,在介紹以前咱們先思考幾個問題:工具
按照上述的幾個問題,EasyUtil-1.0的架構如圖1-1所示,其中綠色部分爲擴展點。this
戳這裏spa
<groupId>com.github.Dorae132</groupId>
<artifactId>easyutil.easyexcel</artifactId>
<version>1.1.0</version>
複製代碼
static class TestValue {
@ExcelCol(title = "姓名")
private String name;
@ExcelCol(title = "年齡", order = 1)
private String age;
@ExcelCol(title = "學校", order = 3)
private String school;
@ExcelCol(title = "年級", order = 2)
private String clazz;
public TestValue(String name, String age, String school, String clazz) {
super();
this.name = name;
this.age = age;
this.school = school;
this.clazz = clazz;
}
}
private List<TestValue> getData(int count) {
List<TestValue> dataList = Lists.newArrayListWithCapacity(10000);
for (int i = 0; i < count; i++) {
dataList.add(new TestValue("張三" + i, "age: " + i, null, "clazz: " + i));
}
return dataList;
}
@Test
public void testAppend() throws Exception {
List<TestValue> dataList = getData(10000);
long start = System.currentTimeMillis();
ExcelProperties<TestValue, File> properties = ExcelProperties.produceAppendProperties("",
"C:\\Users\\Dorae\\Desktop\\ttt\\", "append.xlsx", 0, TestValue.class, 0, null, new AbstractDataSupplier<TestValue>() {
private int i = 0;
@Override
public Pair<List<TestValue>, Boolean> getDatas() {
boolean hasNext = i < 10;
i++;
return Pair.of(dataList, hasNext);
}
});
File file = (File) ExcelUtils.excelExport(properties, FillSheetModeEnums.APPEND_MODE.getValue());
System.out.println("apendMode: " + (System.currentTimeMillis() - start));
}
複製代碼