使用POI应用特定的单元格数据格式

时间:2012-06-05 05:45:42

标签: java excel-2007 apache-poi

我需要将特定数据格式应用于单元格。

XSSFCellStyle cellStyle  = workBook.createCellStyle();          
XSSFDataFormat format = workBook.createDataFormat();
cellStyle.setDataFormat(format.getFormat("m/d/yy h:mm"));
dataCell.setCellType(1); //String
dataCell.setCellStyle(cellStyle);

正在编写数据,但问题是当我打开Excel工作表(在Excel应用程序中)时,格式仅应用 ,单击包含我数据的单元格内部。
然后按Enter键。 只有这样才能应用格式。

如何在不点击每个单元格的情况下应用格式?

2 个答案:

答案 0 :(得分:3)

您的问题是您将单元格设置为字符串。在大多数情况下,单元格格式规则仅适用于数字单元格。它们不适用于字符串单元格,不会格式化(因为它们已经格式化为字符串!)

XSSFCellStyle cellStyle  = workBook.createCellStyle();          
XSSFDataFormat format = workBook.createDataFormat();
cellStyle.setDataFormat(format.getFormat("m/d/yy h:mm"));
dataCell.setCellStyle(cellStyle);

// Set Cell Type not really needed, the setCellValue does it
dataCell.setCellType(Cell.CELL_TYPE_NUMERIC);
// Set a date value (2012-06-05 08:50)
dataCell.setCellValue(new Date(1338878999635));

当你在Excel中打开它时,它应该按预期方式

答案 1 :(得分:1)

这是您将单元格格式更改为all的方式。

Date