简体   繁体   English

如何将日期值设置到单元格

[英]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 设定数值43100.0

I suspect your problem is that you are getting the CellStyle via Cell.getCellStyle and then you are overwriting that CellStyle . 我怀疑你的问题是,你所得到的CellStyle通过Cell.getCellStyle然后要覆盖该CellStyle

CellStyle s are in Excel defined on Workbook level. CellStyleExcelWorkbook级别定义。 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. 所以,如果你做得到CellStyle通过Cell.getCellStyle ,然后覆盖掉CellStyle多次然后只有最后重写将被激活。 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 . 为此,可以在apache poi使用CellUtil 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. 在代码末尾添加updateDateCell = Format(updateDateCell, "dd-MMM-yyyy")

You should get 31-Dec-2017 . 您应该获得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. //更新请参阅Axel Richter的答案https://stackoverflow.com/a/47920182/1053496 ,了解正确的答案。 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();
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Apache POI-如何将单元格值设置为日期格式? - Apache POI - How can I set cell value to date format? 如何将单元格值设置为日期并应用默认的 Excel 日期格式? - How do I set cell value to Date and apply default Excel date format? 如何检查 javafx tableview 中的编辑单元格是否正确,如果不正确:如何将单元格值设置回来? - How can I check if an edit cell in javafx tableview is correct, and if it isn't: how can I set the cell value back? 如何设置单元格值? - How to set cell value? 如何使用JNI在Delphi中设置日期 - How can I set a Date in Delphi with JNI 如何在Alarmmanger上设置日期? - How can I set date on Alarmmanger? 如何在材料日期选择器 Android 中设置当前日期(今天的日期)与所选日期相同 - How can I set current date (Today's date) same as selected date in Material Date Picker Android 如何从 excel 文件中获取特定的单元格值 - How can I get a specific cell value from an excel file 我如何在Wicket AutoCompleTextField中设置值 - how i can set value in Wicket AutoCompleTextField 如何在 android 日期选择器中将特定选择的日期设置为最小日期? (爪哇) - How can I set the specific selected date to min date in android date picker? (java)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM