[英]How to set date field in excel using java apache poi library?
我必须使用 java apache poi 库在 excel 文件(.xlsx 或 .xls)中设置日期字段。
我尝试设置单元格的 cellStyle 和 dataFormat 但它没有将其设置为日期字段而是将其存储为字符串或数字字段。
这是我的代码:
XSSFWorkBook wb = new XSSFWorkBook();
CellStyle cellStyle = wb.createCellStyle();
CreationHelper createHelper = wb.getCreationHelper();
cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("dd-mm-yyyy")); // I have tried different formats here but none working
cell = row.createCell(1);
cell.setCellValue(new Date()); // does not store anything
//cell.setCellValue(new Date().getTime()); // stores the time in milliseconds
//cell.setCellValue(new SimpleDateFormat("dd-MM-yyyy").format(new Date()));
cell.setCellStyle(cellStyle);
我想在excel中将该字段设置为“dd-MM-yyyy”格式,但它可能未在DataFormat中的Apache POI Library BuiltinFormats中定义。
我可能在这里做错了什么,请提出建议。
Excel 中的日期是数字,带有日期格式。 所以你需要相应地格式化你的单元格:
Date date = ...
cellStyle.setDataFormat(wb.getCreationHelper().createDataFormat().getFormat("dd-mm-yyyy"));
cell.setCellType(CellType.NUMERIC);
cell.setCellValue(date);
cell.setCellStyle(cellStyle);
你可以试试这个方法
XSSFFont yourFont = (XSSFFont)workbook.CreateFont();
yourFont.FontHeightInPoints = (short)10;
XSSFCellStyle dateCellStyle = (XSSFCellStyle)workbook.CreateCellStyle();
XSSFDataFormat dateDataFormat = (XSSFDataFormat)workbook.CreateDataFormat();
dateCellStyle.SetDataFormat(dateDataFormat.GetFormat(("dd-mm-yyyy"));
dateCellStyle.SetFont(yourFont);
sheet.SetDefaultColumnStyle(col, dateCellStyle);
老问题,但因为我刚刚遇到过类似的案例,我可以告诉你,你的代码片段在这里应该可以工作。
我猜你的问题出在你显示的代码之外......你是否使用具有现有列格式的excel模板或可能覆盖你的CellStyle的东西?
我使用德语日期格式的工作代码:
CellStyle cellStyle = workbook.createCellStyle();
CreationHelper createHelper = workbook.getCreationHelper();
cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("dd.MM.yyyy"));
... 使用 java.util.Date 对象将样式应用到每个单元格:
cell.setCellValue(date); //java.util.Date date
cell.setCellStyle(cellStyle);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.