How do I set cell value to Date and apply default Excel date format?

前端 未结 6 1687
天涯浪人
天涯浪人 2020-11-29 21:33

I\'ve been using Apache POI for some time to read existing Excel 2003 files programmatically. Now I have a new requirement to create entire .xls files in-memory (still using

6条回答
  •  眼角桃花
    2020-11-29 22:01

    To know the format string used by Excel without having to guess it: create an excel file, write a date in cell A1 and format it as you want. Then run the following lines:

    FileInputStream fileIn = new FileInputStream("test.xlsx");
    Workbook workbook = WorkbookFactory.create(fileIn);
    CellStyle cellStyle = workbook.getSheetAt(0).getRow(0).getCell(0).getCellStyle();
    String styleString = cellStyle.getDataFormatString();
    System.out.println(styleString);
    

    Then copy-paste the resulting string, remove the backslashes (for example d/m/yy\ h\.mm;@ becomes d/m/yy h.mm;@) and use it in the http://poi.apache.org/spreadsheet/quick-guide.html#CreateDateCells code:

    CellStyle cellStyle = wb.createCellStyle();
    CreationHelper createHelper = wb.getCreationHelper();
    cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("d/m/yy h.mm;@"));
    cell = row.createCell(1);
    cell.setCellValue(new Date());
    cell.setCellStyle(cellStyle);
    

提交回复
热议问题