0

Sorry my English not good. My code: styledate

CreationHelper createHelper = workbook.getCreationHelper();
styledate.setDataFormat(
createHelper.createDataFormat().getFormat("d-mmm"));

When I create a excel file, the cell set styledate not display "16-Jun". It's "06/16/2018". If I create input on excel file, it's ok "16-Jun". I want when I create file, cell will display "16-Jun". Thank for your help.

1 Answer 1

2

Whether a cell style will work or not depends on the cell value set into the cell. Your creating of the style looks correct but you do not show how you are setting the cell value into the cell. The style can only work if the cell value is a date value. If it is a string value, then the style cannot work.

The following complete example shows the problem:

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

 }

}
1
  • Thanks for your help Axel Richter
    – kien vu
    Jun 20, 2018 at 17:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.