Apache POI - 生成日期无法相应排序
Apache POI - Generated Date Not Sortable Accordingly
使用 Apache POI API,我已经能够在 Excel 上正确生成整数和浮点数。我可以验证它们是否正确,尤其是当我使用排序功能时。
我只是将值转换为它们各自的类型,API 会处理其余部分。
然而,这种技术不适用于日期(我将它们转换为 java.util.Date
),它们的格式正确,但排序不准确。
有什么建议吗?
我尝试了两种选择:
第一个:cell.setCellValue(new Date(value));
第二个:cell.setCellValue(new SimpleDateFormat("dd/MM/yyyy").format(new Date(value)));
以相反的顺序获取您的代码:
cell.setCellValue(new SimpleDateFormat("dd/MM/yyyy").format(new Date(value)));
不要这样做。它将日期转换为字符串,就像在 Excel 中您进入一个单元格并键入 '01/01/2010
- 前面的 '
强制为字符串
cell.setCellValue(new Date(value));
快到了。您需要遵循 POI instructions on creating a date cell,并将单元格格式化为所需日期格式的日期单元格
例如 dd/mm/yyyy
,一旦接近文件顶部,请执行此操作:
CreationHelper createHelper = wb.getCreationHelper();
CellStyle dateCellStyle = wb.createCellStyle();
dateCellStyle.setDataFormat(
createHelper.createDataFormat().getFormat("dd/MM/yyyy"));
然后为您的单元格设置 + 样式
cell.setCellValue(new Date(value));
cell.setCellStyle(dateCellStyle);
使用 Apache POI API,我已经能够在 Excel 上正确生成整数和浮点数。我可以验证它们是否正确,尤其是当我使用排序功能时。
我只是将值转换为它们各自的类型,API 会处理其余部分。
然而,这种技术不适用于日期(我将它们转换为 java.util.Date
),它们的格式正确,但排序不准确。
有什么建议吗?
我尝试了两种选择:
第一个:cell.setCellValue(new Date(value));
第二个:cell.setCellValue(new SimpleDateFormat("dd/MM/yyyy").format(new Date(value)));
以相反的顺序获取您的代码:
cell.setCellValue(new SimpleDateFormat("dd/MM/yyyy").format(new Date(value)));
不要这样做。它将日期转换为字符串,就像在 Excel 中您进入一个单元格并键入 '01/01/2010
- 前面的 '
强制为字符串
cell.setCellValue(new Date(value));
快到了。您需要遵循 POI instructions on creating a date cell,并将单元格格式化为所需日期格式的日期单元格
例如 dd/mm/yyyy
,一旦接近文件顶部,请执行此操作:
CreationHelper createHelper = wb.getCreationHelper();
CellStyle dateCellStyle = wb.createCellStyle();
dateCellStyle.setDataFormat(
createHelper.createDataFormat().getFormat("dd/MM/yyyy"));
然后为您的单元格设置 + 样式
cell.setCellValue(new Date(value));
cell.setCellStyle(dateCellStyle);