最近用XSSFWorkbook
作Excel導出時遇到了一個問題:當數據達到幾萬行會出現java.lang.OutOfMemoryError: GC overhead limit exceeded
錯誤。html
解決辦法:java
SXSSF(包:org.apache.poi.xssf.streaming)是XSSF的API兼容流式擴展,用於在必須生成很是大的電子表格時使用,而且堆空間有限。SXSSF經過限制對滑動窗口內行的訪問來實現其低內存佔用,而XSSF容許訪問文檔中的全部行。再也不在窗口中的舊行變得不可訪問,由於它們被寫入磁盤。apache
詳細介紹請查看:poi.apache.org/components/…dom
測試類:xss
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
/** * SXSSFWorkbook測試 * * @author 王曉安 */
public class SXSSFWorkbookTest {
private static SXSSFWorkbook getWorkbook(List<String> title, List<? extends List<?>> data) {
SXSSFWorkbook workbook = new SXSSFWorkbook();
// 添加一個sheet
final Sheet sheet = workbook.createSheet();
// 構建title
final Row titleRow = sheet.createRow(0);
for (int i = 0; i < title.size(); i++) {
final Cell titleRowCell = titleRow.createCell(i);
titleRowCell.setCellValue(title.get(i));
}
// 填充數據
for (int i = 0; i < data.size(); i++) {
final Row row = sheet.createRow(i + 1);
final List<?> dataRow = data.get(i);
for (int j = 0; j < dataRow.size(); j++) {
final Cell cell = row.createCell(j);
final Object value = dataRow.get(j);
cell.setCellValue(value == null ? "" : String.valueOf(value));
}
}
return workbook;
}
public static void main(String[] args) {
int col = 10;
int row = 100_0000;
final List<String> title = IntStream.rangeClosed(1, col)
.mapToObj(value -> "第" + value + "列")
.collect(Collectors.toList());
final List<List<Double>> data = IntStream.range(0, row)
.mapToObj(value ->
IntStream.range(0, col)
.mapToObj(ignore -> Math.random())
.collect(Collectors.toList())
)
.collect(Collectors.toList());
final LocalDateTime start = LocalDateTime.now();
final SXSSFWorkbook workbook = getWorkbook(title, data);
try (OutputStream outputStream = new FileOutputStream("/data/temp/測試.xlsx")) {
workbook.write(outputStream);
// 丟棄在磁盤上備份此工做簿的臨時文件
workbook.dispose();
} catch (IOException e) {
e.printStackTrace();
}
final LocalDateTime end = LocalDateTime.now();
final Duration duration = Duration.between(start, end);
System.out.println("生成Excel花費時間:" + duration);
}
}
複製代碼
生成一百萬行的Excel時間大約32秒:測試
生成的Excel大小以下:spa
算上標題和數據共一百萬零一行:code