简体   繁体   中英

XSSF Apache POI

I used the below for setting default column style in XSSF sheet? but this is not working can anyone suggest the bug fix.

format = workbook.createDataFormat();
style = workbook.createCellStyle();
style.setDataFormat(format.getFormat("@"));
sheet.setDefaultColumnStyle(1, style); 

As of POI 4.1.0 it is working with SXSSF, but with a caveat. The default column style only defines which style will be applied when users enter data into empty cells in the sheet created by POI. If you create cells and enter data through POI, the default format does not apply, you have to use setCellStyle(CellStyle) .

Eg for text styles:

private CellStyle createTextFormat(SXSSFWorkbook workbook) {
    DataFormat fmt = workbook.createDataFormat();
    CellStyle textStyle = workbook.createCellStyle();
    textStyle.setDataFormat(fmt.getFormat("@"));
    return textStyle;
}

// then do both:
int columnIndex = 0;
sheet.setDefaultColumnStyle(columnIndex, textFormat)

SXSSFCell cell = row.createCell(0);
cell.setCellStyle(textFormat);
cell.setCellValue("0100");

Probably this bug is causing you headaches. Trying your code with Apache POI 3.7 I get the added effect that the second column gets hidden (width = 0) and the format is not applied.

Cheers, Wim

PS Note that I talk about the second column, which is what your code is really referring to; if you wanted to apply the style to the first column you should have used 0 (zero-based).

Try this it will work:

       style.setDataFormat(HSSFDataFormat.getBuiltinFormat("@"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM