XLSX 的 CellStyle 数据格式

CellStyle dataformat for XLSX

我有一些代码,例如:

CellStyle cs2 = wb.createCellStyle();
CellStyle cs4 = wb.createCellStyle();
cs4.setDataFormat(HSSFDataFormat.getBuiltinFormat("CELL_TYPE_NUMERIC"));
cs2.setDataFormat(HSSFDataFormat.getBuiltinFormat("text"));

这是为了创建 xls 报告。我如何更改此代码以创建 XLSX 报告?

下面的方法行得通吗?

XSSFDataFormat format = (XSSFDataFormat) wb.createDataFormat();

            cs2.setDataFormat(format.getFormat("text"));

请帮忙。

谢谢

是的,内置格式仍适用于 Apache POI 中的 .xlsx 电子表格。

即使 XSSFDataFormat#getFormat(String) don't mention it, the source code 的 Javadocs 告诉所有:

public short getFormat(String format) {
    int idx = BuiltinFormats.getBuiltinFormat(format);
    if(idx == -1) idx = stylesSource.putNumberFormat(format);
    return (short)idx;
}

它会先在​​BuiltinFormats对象中查找数据格式,如果没有找到,则创建一个新的。

我已经在创建 .xlsx 电子表格时对此进行了测试,并且使用 "text" 有效。我创建了数字单元格,并将这些单元格设置为 CellStyle,并使用 "text" 创建了 XSSFDataFormat,并且这些单元格在生成的电子表格中采用了 "text" 样式。