background
Need to write an exported Excel function today, but found that when the amount of data to 30,000, the number of columns in the 23, out of memory, CPU 100%, the test environment direct blow. Found in the local test, export around 3000 data, the heap memory transient increase around 500M. Then found SXSSFWorkbook
the class.
Brief introduction
SXSSFWorkbook
Need to poi-ooxml
pack 3.8
and began to support the above, my side is suitable for use 3.9
version, essentially a XSSFWorkbook
class ( Excel2007
), the way it used to be adopted 硬盘空间
to significantly reduce 堆内存
the footprint, create a temporary file in the temporary folder for the System directory and all greater than the number agreed upon rows of data are stored in a temporary file, but not all in memory, the memory storing only the latest of a number of pieces of data agreement, in order to achieve hard disk space for memory space to avoid running out of memory
Use
Excel indistinguishable from the normal derivation method, just replaced instantiatedSXSSFWorkbook
SXSSFWorkbook workbook = null;
OutputStream outputStream = null;
try {
outputStream = response.getOutputStream();
//创建工作簿
workbook = new SXSSFWorkbook();
// 打开压缩功能 防止占用过多磁盘
workbook.setCompressTempFiles(true);
// 创建一个工作表
Sheet sheet = workbook.createSheet("表名");
// 创建一行
Row titleRow = sheet.createRow(0);
// 创建一个单元格
Cell cell = titleRow.createCell(0);
// 给单元格赋值
cell.setCellValue("内容");
// 将工作簿写入输出流
workbook.write(outputStream);
} catch (Exception e) {
e.printStackTrace();
}finally {
if (workbook != null) {
//使用完毕后将产生的临时文件删除 防止将磁盘搞满
workbook.dispose();
}
if (outputStream != null) {
outputStream.close();
}
}
复制代码
important point
-
Preferably the compressed mode is turned on
workbook.setCompressTempFiles(true);
so that temporary files can greatly reduce the volume -
Released after use
workbook.dispose();
to prevent temporary files has been increased to explode hard disk