首页 > 解决方案 > 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”。感谢您的帮助。

标签: javaapacheapache-poi

解决方案


单元格样式是否有效取决于设置到单元格中的单元格值。您创建的样式看起来是正确的,但您没有显示如何将单元格值设置到单元格中。仅当单元格值为日期值时,该样式才有效。如果它是字符串值,则样式无法正常工作。

以下完整示例显示了该问题:

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();
  }

 }

}

推荐阅读