如何使用java apache poi库在excel中设置日期字段? [英] How to set date field in excel using java apache poi library?
问题描述
我必须使用 java apache poi 库在 excel 文件(.xlsx 或 .xls)中设置日期字段.
I have to set the date field in excel file (.xlsx or .xls) using java apache poi library.
我尝试设置单元格的 cellStyle 和 dataFormat 但它没有将其设置为日期字段而是将其存储为字符串或数字字段.
I have tried setting the cellStyle and dataFormat of the cell but it does not set it as date field and instead stores it as string or numeric field.
这是我的代码:
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 库内置格式中定义.
I want to set the field as "dd-MM-yyyy" format in excel but it might not be defined in Apache POI Library BuiltinFormats in DataFormat.
我可能在这里做错了什么,请提出建议.
I may be doing something wrong here, please suggest.
推荐答案
Excel 中的日期是数字,带有日期格式.所以你需要相应地格式化你的单元格:
Dates in Excel are numeric, with a date formatting. So you need to format your cell accordingly:
Date date = ...
cellStyle.setDataFormat(wb.getCreationHelper().createDataFormat().getFormat("dd-mm-yyyy"));
cell.setCellType(CellType.NUMERIC);
cell.setCellValue(date);
cell.setCellStyle(cellStyle);
这篇关于如何使用java apache poi库在excel中设置日期字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!