java - Apache POI - 如何将单元格值设置为日期格式?
问题描述
对不起我的英语不好。我的代码:styledate
CreationHelper createHelper = workbook.getCreationHelper();
styledate.setDataFormat(
createHelper.createDataFormat().getFormat("d-mmm"));
当我创建一个 excel 文件时,单元格集 styledate 不显示“16-Jun”。现在是“2018 年 6 月 16 日”。如果我在 excel 文件上创建输入,则可以“16-Jun”。我希望在创建文件时,单元格将显示“16-Jun”。感谢您的帮助。
解决方案
单元格样式是否有效取决于设置到单元格中的单元格值。您创建的样式看起来是正确的,但您没有显示如何将单元格值设置到单元格中。仅当单元格值为日期值时,该样式才有效。如果它是字符串值,则样式无法正常工作。
以下完整示例显示了该问题:
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class CreateExcelCustomDateFormat {
public static void main(String[] args) throws Exception {
Workbook workbook = new XSSFWorkbook();
CreationHelper createHelper = workbook.getCreationHelper();
CellStyle styledate = workbook.createCellStyle();
styledate.setDataFormat(createHelper.createDataFormat().getFormat("d-MMM"));
Sheet sheet = workbook.createSheet();
Cell cell;
//This sets date value into cell and does formatting it.
cell = sheet.createRow(0).createCell(0);
cell.setCellValue(java.util.Date.from(java.time.Instant.now()));
cell.setCellStyle(styledate);
String date = "06/17/2018";
//This sets string value into cell. There the format will not work.
cell = sheet.createRow(1).createCell(0);
cell.setCellValue(date);
cell.setCellStyle(styledate);
//This converts string value to date and then sets the date into cell. There the format will work.
cell = sheet.createRow(2).createCell(0);
cell.setCellValue(java.util.Date.from(
java.time.LocalDate.parse(
date,
java.time.format.DateTimeFormatter.ofPattern("MM/dd/yyyy")
).atStartOfDay(java.time.ZoneId.systemDefault()).toOffsetDateTime().toInstant()
)); //yes, java.time is a monster in usage ;-)
cell.setCellStyle(styledate);
try (FileOutputStream fos = new FileOutputStream("CreateExcelCustomDateFormat.xlsx")) {
workbook.write(fos);
workbook.close();
}
}
}
推荐阅读
- visual-studio - Visual Studio 2019“解决方案资源管理器”“查看代码”图标 C#
- python - 以相等的比例设置 matplotlib 3D 轴
- flutter - 是否可以在颤动的 TextFormField 中显示外键数据
- python - 调用 PutObject 操作时发生错误(InvalidArgument):计算的键的 MD5 哈希与提供的哈希不匹配
- database - 活动记录错误,是不是输入错误?
- django - 为什么 serializer.is_valid() 在这种情况下总是假的?
- asp.net-core - SQLDependancy 滞后
- c++ - 使用 UWP/c++ 录制具有同步关联元数据的视频
- flutter - Flutter listview 总是扩展到可用宽度
- sql - DBeaver 右键单击数据库和工具 -> 执行脚本:如何指定哪个模式?