Java POI export large amounts of data using Excel

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 SXSSFWorkbookthe class.

Brief introduction

SXSSFWorkbookNeed to poi-ooxmlpack 3.8and began to support the above, my side is suitable for use 3.9version, essentially a XSSFWorkbookclass ( 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

Guess you like

Origin juejin.im/post/5dd66fea6fb9a05a987e8a9f