Apache POI Excel cell formatting is not working be

2019-06-14 17:38发布

问题:

I have a requirement where I need to generate a report for all transaction for a given period, and I need to apply the cell format accordingly. In this case cell formatting is not working especially for Date after creating 32748 cells in the sheet. This seems to be bug in the API, please provide some inputs if anybody already faced this issue and found any fix.

For reference, here is the sample code :

public class TestFormat {

public static void main(String args[]){
    try {
    HSSFWorkbook wb = new HSSFWorkbook();
    HSSFSheet sheet = wb.createSheet("Excel Sheet");

    HSSFDataFormat format = wb.createDataFormat();


    for(int i = 1; i<65535;i++ ) {

            HSSFRow row = sheet.createRow(i);
            HSSFCell cell = row.createCell(1);
            HSSFCellStyle style = wb.createCellStyle();
            cell.setCellValue((Date) new Date());
            style.setDataFormat(format.getFormat("MM/dd/yyyy HH:mm:ss"));
            cell.setCellStyle(style);

    }
    FileOutputStream fileOut;

        fileOut = new FileOutputStream("c:\\test\\excelFile.xls");
         wb.write(fileOut);
            fileOut.close();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    System.out.println("Data is saved in excel file.");
}

}

回答1:

You're creating your cell style inside the loop. Don't!

Excel has a limit on the number of cell styles that it allows in the file format. What you need to do is to move the creation/setup of your cell style outside of your loop, so it's only created once, and it should be fine

The core part of your code would then look something like:

HSSFDataFormat format = wb.createDataFormat();
HSSFCellStyle style = wb.createCellStyle();
cell.setCellValue((Date) new Date());
style.setDataFormat(format.getFormat("MM/dd/yyyy HH:mm:ss"));

for(int i = 1; i<65535;i++ ) {
        HSSFRow row = sheet.createRow(i);
        HSSFCell cell = row.createCell(1);
        cell.setCellStyle(style);
}


标签: apache-poi