您好我正在使用Java中的apachePOI生成xls文件。我有日期栏目。现在问题是Excel从默认操作系统设置中选择日期格式。
我有一个问题,我希望Excel总是选择dd-mm-yyyy。但是操作系统设置为美国的系统,它选择了mm-dd-yyyy。所以17-2-2017这样的有效日期在美国系统中无效,因为没有第17个月。
所以我的问题是我可以强制Excel使用我想要的日期格式。换句话说,我可以限制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");
}
}
答案 0 :(得分:1)
发布的代码不完整但似乎单元格格式设置为dd-mm-yyyy。
但是,代码采用Date
:
Date creationDate = inputCreationDateFormat.parse(inputDate);
并将其转换为其他类型(String
?)以获取实际的单元格值。
cell.setCellValue(outputCreationDateFormat.format(creationDate));
相反,只需使用Date
:
cell.setCellValue(creationDate);
因此Excel可以将格式应用于日期值。
以下是多种格式的示例:
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();
}
}