在XSSFWorkbook中保存时,日期字段未以正确的格式保存

时间:2019-07-15 10:14:06

标签: excel spring-boot apache-poi

我正在尝试从REST API中以excel(即.xlsx格式)保存用户定义的对象列表。它会创建一个 XSSFWorkbook ,并将数据存储在工作簿中。返回 ByteArrayInputStream 。在我的Entity类中,我将其存储为

@Column(name = "created_date", columnDefinition = "timestamp with time zone") @Temporal(TemporalType.TIMESTAMP) private Date createdDate;

  

这是用于将列表写入服务中的工作簿的代码。

XSSFWorkbook workbook = new XSSFWorkbook();     
    // Create a blank sheet
    XSSFSheet sheet = workbook.createSheet("Survey");
    String[] columns = {"Name","createdDate"};
     ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    int rownum = 1;
    for (Integer key : keyset) {
        // this creates a new row in the sheet
        Row row = sheet.createRow(rownum++);
        Survey survey = data.get(key);
        row.createCell(0).setCellValue(survey.getName());
        row.createCell(1).setCellValue(survey.getCreatedDate());
    }
    try {           
        workbook.write(outputStream);
        workbook.close();
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        workbook.close();
    }
return new ByteArrayInputStream(outputStream.toByteArray());

在控制器中,我设置标题contentTypecontent-disposition并返回为 ResponseEntity

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
 headers.add("Content-Disposition", "attachment; filename=" + "AuditTrial.xlsx");
return ResponseEntity.ok().headers(headers).body(isr);

实际数据如下所示,即数据来自数据库

[{ "createdDate": "2019-07-15T07:45:48.555Z", "name": "abc" },{ "createdDate": "2019-07-15T07:45:48.555Z", "name": "xyz" }]

问题是当我尝试打开将在调用上述api后产生的Excel时,日期格式不正确。如下。

enter image description here

如何在Excel中以正确的格式保存日期?我在哪里弄错了。欢迎任何帮助和建议。

1 个答案:

答案 0 :(得分:4)

您的实体与apache poi的细胞无关。 在您实体的createdDate中,您将其设置为时间戳记,但它不会告诉您如何设置poi。

要创建日期单元格时,您需要:

  • 创建CellStyle
  • 设置该CellStyle的日期格式
  • 将该CellStyle应用于所需的单元格

例如:

CellStyle cellStyle = wb.createCellStyle();
cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("m/d/yy h:mm"));

...

for (Integer key : keyset) {
    // this creates a new row in the sheet
    Row row = sheet.createRow(rownum++);
    Survey survey = data.get(key);
    row.createCell(0).setCellValue(survey.getName());
    Cell dateCell = row.createCell(1);
    dateCell.setCellStyle(cellStyle);
    dateCell.setCellValue(survey.getCreatedDate());
}