使用SXSSFWorkbook来导出excel

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

  • BigGridDemo

你可能感兴趣的:(java)