简体   繁体   中英

How can I set Date value into cell

Following is my code:

String monthEndDate = "31-Dec-17";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yy",java.util.Locale.ENGLISH);
XSSFCell updateDateCell = sheet.getRow(rownumber).getCell(15);
XSSFCellStyle cellStyle = (XSSFCellStyle)updateDateCell.getCellStyle();
CreationHelper createHelper = wb.getCreationHelper();
cellStyle.setDataFormat(
createHelper.createDataFormat().getFormat("dd-MMM-yy"));
Date updateDate = sdf.parse(monthEndDate);
updateDateCell.setCellValue(updateDate);
updateDateCell.setCellStyle(cellStyle);

It is setting numeric value 43100.0

I suspect your problem is that you are getting the CellStyle via Cell.getCellStyle and then you are overwriting that CellStyle .

CellStyle s are in Excel defined on Workbook level. That means, not each cell has it's own cell style but cells share cell styles defined on workbook level.

So if you do the getting the CellStyle via Cell.getCellStyle and then overwriting that CellStyle multiple times then only the last overwriting will be active. So I suspect, your complete code overwrites the same cell style, gotten from another cell, with another number format after you have overwritten it with the date number format.

The easy conclusion could be to really give each cell it's own cell style. But this is also wrong since there is a limit number of cell styles in a workbook. So we need

  1. Having as much own cell styles as needed.
  2. Having as much cell styles shared as possible.

To achieve this CellUtil can be used in apache poi . This provides methods only to create a new cell style if there is not already the same cell style defined in the workbook and simply to use that cell style if there is already the same cell style defined in the workbook.

Example:

import java.io.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;

import org.apache.poi.ss.util.CellUtil;

import java.text.SimpleDateFormat;
import java.util.Date;

import java.util.Map;
import java.util.HashMap;

public class ExcelSetDateValue {

 public static void main(String[] args) throws Exception {
  XSSFWorkbook wb = (XSSFWorkbook)WorkbookFactory.create(new FileInputStream("ExcelTest.xlsx"));

  //possiby we need data formats
  DataFormat dataFormat = wb.createDataFormat();

  //get sheet and set row number
  XSSFSheet sheet = wb.getSheetAt(0);
  int rownumber = 3;

  //get the date
  String monthEndDate = "31-Dec-17";
  SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yy", java.util.Locale.ENGLISH);
  Date updateDate = sdf.parse(monthEndDate);

  //set date as cell value
  XSSFCell updateDateCell = sheet.getRow(rownumber).getCell(15);
  updateDateCell.setCellValue(updateDate);

  //use CellUtil to set the CellStyleProperties
  Map<String, Object> properties = new HashMap<String, Object>();
  properties.put(CellUtil.DATA_FORMAT, dataFormat.getFormat("dd-MMM-yy"));
  CellUtil.setCellStyleProperties(updateDateCell, properties);

  wb.write(new FileOutputStream("ExcelTestNew.xlsx"));
  wb.close();
 }  
}

Add updateDateCell = Format(updateDateCell, "dd-MMM-yyyy") at the end of your code.

You should get 31-Dec-2017 .

This is an example which I already have for formatting date, you can reuse the part of it ( I marked the relevant lines of code). It's tested and working fine, if any issue let me know.

//UPDATE Please see Axel Richter's answer https://stackoverflow.com/a/47920182/1053496 for the correct answer. In my example, I'm storing date as String instead of Date object which is not the recommended way

import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.xssf.usermodel.*;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;



public class WriteExcelBasic {
    public static void main(String[] args) throws IOException {

        String excelFileName = "/Users/home/Test3.xls";
        FileOutputStream fos = new FileOutputStream(excelFileName);


        XSSFWorkbook wb = new XSSFWorkbook();
        XSSFCellStyle style = wb.createCellStyle();

        XSSFSheet sheet = wb.createSheet("sheet");
        XSSFFont urlFont = wb.createFont();
        style.setFont(urlFont);
        String monthEndDate = "31-Dec-17";
        DataFormat df = wb.createDataFormat(); //these 3 lines  are enough
         short dateFormat = df.getFormat("dd-MMM-yy"); // 2nd 
        style.setDataFormat(dateFormat); // 3rd


        for (int r = 0; r < 1; r++) {
            XSSFRow row = sheet.createRow(r);
            row.setHeight((short) -1);
            for (int c = 0; c < 3; c++) {
                XSSFCell cell = row.createCell(c);
                String ss = "31-Dec-17";
                cell.setCellValue(ss);
                    style.setWrapText(true);
                cell.setCellStyle(style);
            }
        }

        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            wb.write(baos);
            byte[] myByteArray = baos.toByteArray();
            fos.write(myByteArray);
            fos.flush();
        }
        finally {
            wb.close();
            fos.close();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM