Using custom colors with SXSSF (Apache POI)

后端 未结 3 794
广开言路
广开言路 2021-01-12 02:48

I am trying to write a huge excel file, my requirement allows me to write the row and forget, so i am using SXSSF which allows to keep only a few number of rows in memory an

3条回答
  •  余生分开走
    2021-01-12 03:26

    To avoid the need of typecast for the cellStyles, create first a XSSFWorkbook with cellStyles (XSSFCellStyle) applying the custom colors and then wrap it with a SXSSFWorkbook constructor like the sample below:

    /**
     * Sample based on POI Spreadsheet How-To.
     * 
     * @see SXSSFWorkbook
     */
    public static void main(String[] args) throws Throwable {
    
        XSSFWorkbook xssfWorkbook = new XSSFWorkbook();
    
        XSSFColor colorGrey = new XSSFColor(new Color(210, 210, 210));
        XSSFCellStyle cellStyleGrey = xssfWorkbook.createCellStyle();
        cellStyleGrey.setFillPattern(CellStyle.SOLID_FOREGROUND);
        cellStyleGrey.setFillForegroundColor(colorGrey);
    
        // keep 100 rows in memory, exceeding rows will be flushed to disk
        SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook(xssfWorkbook, 100);
        Sheet sheet = sxssfWorkbook.createSheet();
    
        for (int rownum = 0; rownum < 1000; rownum++) {
            Row row = sheet.createRow(rownum);
            for (int cellnum = 0; cellnum < 10; cellnum++) {
                Cell cell = row.createCell(cellnum);
                String address = new CellReference(cell).formatAsString();
                cell.setCellValue(address);
    
                // for even rows apply the grey cellStyle
                if (rownum % 2 == 0) {
                    cell.setCellStyle(cellStyleGrey);
                }
            }
    
        }
    
        // Omitted asserts block from original sample...
    
        FileOutputStream out = new FileOutputStream("/temp/sxssf.xlsx");
        sxssfWorkbook.write(out);
        out.close();
    
        // dispose of temporary files backing this workbook on disk
        sxssfWorkbook.dispose();
    }
    

提交回复
热议问题