I have some code like :
CellStyle cs2 = wb.createCellStyle();
CellStyle cs4 = wb.createCellStyle();
cs4.setDataFormat(HSSFDataFormat.getBuiltinFormat("CELL_TYPE_NUMERIC"));
cs2.setDataFormat(HSSFDataFormat.getBuiltinFormat("text"));
this is for creating xls reports. How do i change this code to create XLSX reports ?
will the following work ?
XSSFDataFormat format = (XSSFDataFormat) wb.createDataFormat();
cs2.setDataFormat(format.getFormat("text"));
Please help.
Thanks
Yes, built-in formats will still work with .xlsx spreadsheets in Apache POI.
Even if the Javadocs for XSSFDataFormat#getFormat(String)
don't mention it, the source code tells all:
public short getFormat(String format) {
int idx = BuiltinFormats.getBuiltinFormat(format);
if(idx == -1) idx = stylesSource.putNumberFormat(format);
return (short)idx;
}
It will look up the data format in the BuiltinFormats
object first, and if not found, it will create a new one.
I've tested this on creating a .xlsx spreadsheet, and using "text"
works. I created numeric cells, and I set those cells to a CellStyle
with a XSSFDataFormat
created with "text"
, and the cells are "text"-styled in the resultant spreadsheet.