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));
}
复制代码