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

标签 excel spring-boot apache-poi

我正在尝试以 excel 格式保存用户定义对象的列表,即来自 REST API 的 .xlsx 格式。这会创建一个 XSSF 工作簿 并将数据存储在工作簿中。返回 字节数组输入流 .在我的实体类中,我将其存储为
@Column(name = "created_date", columnDefinition = "timestamp with time zone") @Temporal(TemporalType.TIMESTAMP) private Date createdDate;

Here is piece of code for writing list to Workbook in service.


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());

在 Controller 中,我正在设置标题 contentTypecontent-disposition并返回 响应实体 .
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中以正确的格式保存日期?我在哪里弄错了。欢迎任何帮助和建议。

最佳答案

您的实体与 apache poi 的单元格无关。
在您的实体的 createdDate 中,您设置它是一个时间戳,但它不会告诉 apache 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());
    }
    

    关于excel - 在 XSSFWorkbook 中保存时日期字段未以正确格式保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57037636/

    相关文章:

    tomcat - 在 tomcat 8 上部署 war 时未加载 Spring Boot 应用程序

    java - 如何在 Spring Boot 中设置 Web 服务响应的媒体类型?

    java - 如何使用 HSSFFont 以十进制数设置字体

    java - 如何将动态列数据导出到excel

    java - 使用java POI打印excel中的数据

    Excel 2列比较: duplicate in one column,但作为对唯一

    python - 如何从 R 中的 xlsx 文件中检测 "strikethrough"样式

    java - 根据 Activity 配置文件从自定义文件加载属性

    excel - 如何使用空间 MS Excel 拆分数据

    正则表达式从字符串中提取第一组数字