使用SXSSFWorkbook來匯出excel

weixin_34253539發表於2017-08-01

SXSSFWorkbook是XSSFWorkbook的Streaming版本,實現了"BigGridDemo"的策略,在匯出大量資料的時候,可以避免OOM。

使用例項

@Test
    public void testWriteLargeData() throws IOException {
        FileInputStream inputStream = new FileInputStream("mytemplate.xlsx");
        XSSFWorkbook wb_template = new XSSFWorkbook(inputStream);
        inputStream.close();

        SXSSFWorkbook wb = new SXSSFWorkbook(wb_template);
        wb.setCompressTempFiles(true);

        SXSSFSheet sh = (SXSSFSheet) wb.getSheetAt(0);
        sh.setRandomAccessWindowSize(100);// keep 100 rows in memory, exceeding rows will be flushed to disk
        for(int rownum = 4; rownum < 100000; rownum++){
            Row row = sh.createRow(rownum);
            for(int cellnum = 0; cellnum < 10; cellnum++){
                Cell cell = row.createCell(cellnum);
                String address = new CellReference(cell).formatAsString();
                cell.setCellValue(address);
            }

        }


        FileOutputStream out = new FileOutputStream("tempsxssf.xlsx");
        wb.write(out);
        out.close();
        // dispose of temporary files backing this workbook on disk
        wb.dispose();
    }

doc

相關文章