Apache POI Excel cell formatting is not working beyond 32748 cell in a sheet

為{幸葍}努か 提交于 2019-12-23 06:14:54

问题


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);
}


来源:https://stackoverflow.com/questions/14618081/apache-poi-excel-cell-formatting-is-not-working-beyond-32748-cell-in-a-sheet

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!