限制Excel使用apachePOI在Java中不使用OS默认date格式

您好我正在使用Java中的apachePOI生成xls文件。 我有date栏目。 现在的问题是,Excel从默认的操作系统设置中selectdate格式。

我有一个问题,我希望Excel总是selectdd-mm-yyyy。 但是操作系统设置为美国的系统会selectmm-dd-yyyy。 所以像17-2-2017这样的有效date在美国系统中是无效的,因为没有17个月。

所以我的问题是我可以强制Excel使用我想要的date格式。 换句话说,我可以限制Excel不使用操作系统设置。 如果不可能的话,赞赏任何其他解决方法。 谢谢。

码:

private static void doCreate() throws FileNotFoundException, ParseException { Workbook workbook; Row row; Sheet spreadsheet; workbook = new HSSFWorkbook(); spreadsheet = workbook.createSheet("Order Details"); dateCellStyle = workbook.createCellStyle(); // LocaleUtil.setUserTimeZone(LocaleUtil.TIMEZONE_UTC); // // Locale.setDefault(); // final String excelFormatPattern = DateFormatConverter.convert(Locale.JAPANESE, "dd MMMM, yyyy"); // // final DataFormatter dataFormatter = new DataFormatter(Locale.ENGLISH); final short df = workbook.createDataFormat().getFormat("dd-mm-yyyy"); dateCellStyle.setDataFormat(df); final String inputDate = "2017-10-24"; row = spreadsheet.createRow(0); final Cell cell = row.createCell(0); final Date creationDate = inputCreationDateFormat.parse(inputDate); cell.setCellValue(outputCreationDateFormat.format(creationDate)); cell.setCellStyle(dateCellStyle); final FileOutputStream out = new FileOutputStream(new File("Writesheet.xls")); try { workbook.write(out); workbook.close(); } catch (final IOException e) { } System.out.println("Writesheet.xls written successfully"); } } 

发布的代码不完整,但它显示单元格格式被设置为dd-mm-yyyy。

但是,代码采用Date

 Date creationDate = inputCreationDateFormat.parse(inputDate); 

并将其转换为其他types( String ?)的实际单元格值。

 cell.setCellValue(outputCreationDateFormat.format(creationDate)); 

相反,只需使用Date

 cell.setCellValue(creationDate); 

所以Excel可以将格式应用于date值。

这里有一个多种格式的例子:

 public class XlsApp { public static void main(String[] args) throws IOException { XlsApp app = new XlsApp(); app.doCreate(); } private void doCreate() throws IOException { Workbook workbook = new HSSFWorkbook(); CellStyle mmddyyyy = workbook.createCellStyle(); mmddyyyy.setDataFormat(workbook.createDataFormat().getFormat("mm-dd-yyyy")); CellStyle ddmmyyyy = workbook.createCellStyle(); ddmmyyyy.setDataFormat(workbook.createDataFormat().getFormat("dd-mm-yyyy")); Sheet sheet = workbook.createSheet(); for (int r = 0; r < 10; r++) { Date date = new Date(System.currentTimeMillis() - ThreadLocalRandom.current().nextInt()); Row row = sheet.createRow(r); Cell cell = row.createCell(0); cell.setCellStyle(mmddyyyy); cell.setCellValue(date); cell = row.createCell(1); cell.setCellStyle(ddmmyyyy); cell.setCellValue(date); } sheet.autoSizeColumn(0); sheet.autoSizeColumn(1); FileOutputStream out = new FileOutputStream(new File("c:\\temp\\test.xls")); workbook.write(out); workbook.close(); } }