Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何将单元格值设置为日期并应用默认的Excel日期格式?_Java_Date_Apache Poi - Fatal编程技术网

Java 如何将单元格值设置为日期并应用默认的Excel日期格式?

Java 如何将单元格值设置为日期并应用默认的Excel日期格式?,java,date,apache-poi,Java,Date,Apache Poi,一段时间以来,我一直在使用ApachePOI以编程方式读取现有的Excel2003文件。现在我有了一个新的需求,即在内存中创建整个.xls文件(仍然使用ApachePOI),然后在最后将它们写入一个文件。我遇到的唯一问题是如何处理带有日期的单元格 考虑以下代码: Date myDate = new Date(); HSSFCell myCell; // code that assigns a cell from an HSSFSheet to 'myCell' would go here...

一段时间以来,我一直在使用ApachePOI以编程方式读取现有的Excel2003文件。现在我有了一个新的需求,即在内存中创建整个.xls文件(仍然使用ApachePOI),然后在最后将它们写入一个文件。我遇到的唯一问题是如何处理带有日期的单元格

考虑以下代码:

Date myDate = new Date();
HSSFCell myCell;
// code that assigns a cell from an HSSFSheet to 'myCell' would go here...
myCell.setCellValue(myDate);
当我将包含此单元格的工作簿写入文件并用Excel打开它时,该单元格显示为一个数字。是的,我知道Excel将其“日期”存储为1900年1月1日以来的天数,这就是单元格中的数字所表示的

问题:我可以在POI中使用什么API调用来告诉它我希望将默认日期格式应用于我的日期单元格?

理想情况下,我希望电子表格单元格以默认日期格式显示,如果用户在Excel中手动打开电子表格并键入Excel识别为日期的单元格值,Excel将为其分配相同的默认日期格式。


此示例用于处理.xlsx文件类型。此示例来自用于创建.xslx电子表格的.jsp页面

import org.apache.poi.xssf.usermodel.*; //import needed

XSSFWorkbook  wb = new XSSFWorkbook ();  // Create workbook
XSSFSheet sheet = wb.createSheet();      // Create spreadsheet in workbook
XSSFRow row = sheet.createRow(rowIndex); // Create the row in the spreadsheet


//1. Create the date cell style
XSSFCreationHelper createHelper = wb.getCreationHelper();
XSSFCellStyle cellStyle         = wb.createCellStyle();
cellStyle.setDataFormat(
createHelper.createDataFormat().getFormat("MMMM dd, yyyy")); 

//2. Apply the Date cell style to a cell

//This example sets the first cell in the row using the date cell style
cell = row.createCell(0);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);

此代码示例可用于更改日期格式。这里我想从yyyy-MM-dd改为dd-MM-yyyy。这里
pos
是列的位置

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

class Test{ 
public static void main( String[] args )
{
String input="D:\\somefolder\\somefile.xlsx";
String output="D:\\somefolder\\someoutfile.xlsx"
FileInputStream file = new FileInputStream(new File(input));
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> iterator = sheet.iterator();
Cell cell = null;
Row row=null;
row=iterator.next();
int pos=5; // 5th column is date.
while(iterator.hasNext())
{
    row=iterator.next();

    cell=row.getCell(pos-1);
    //CellStyle cellStyle = wb.createCellStyle();
    XSSFCellStyle cellStyle = (XSSFCellStyle)cell.getCellStyle();
    CreationHelper createHelper = wb.getCreationHelper();
    cellStyle.setDataFormat(
        createHelper.createDataFormat().getFormat("dd-MM-yyyy"));
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Date d=null;
    try {
        d= sdf.parse(cell.getStringCellValue());
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        d=null;
        e.printStackTrace();
        continue;
    }
    cell.setCellValue(d);
    cell.setCellStyle(cellStyle);
   }

file.close();
FileOutputStream outFile =new FileOutputStream(new File(output));
workbook.write(outFile);
workbook.close();
outFile.close();
}}
import org.apache.poi.ss.usermodel.Cell;
导入org.apache.poi.ss.usermodel.CellStyle;
导入org.apache.poi.ss.usermodel.CreationHelper;
导入org.apache.poi.ss.usermodel.Row;
导入org.apache.poi.xssf.usermodel.XSSFCellStyle;
导入org.apache.poi.xssf.usermodel.XSSFColor;
导入org.apache.poi.xssf.usermodel.xssfont;
导入org.apache.poi.xssf.usermodel.xssfheet;
导入org.apache.poi.xssf.usermodel.xssf工作簿;
类测试{
公共静态void main(字符串[]args)
{
String input=“D:\\somefolder\\somefile.xlsx”;
字符串输出=“D:\\somefolder\\someoutfile.xlsx”
FileInputStream文件=新FileInputStream(新文件(输入));
XSSF工作簿=新XSSF工作簿(文件);
XSSFSheet sheet=workbook.getSheetAt(0);
迭代器迭代器=sheet.Iterator();
Cell=null;
行=空;
row=iterator.next();
int pos=5;//第五列是日期。
while(iterator.hasNext())
{
row=iterator.next();
单元格=行。getCell(位置1);
//CellStyle CellStyle=wb.createCellStyle();
XSSFCellStyle cellStyle=(XSSFCellStyle)cell.getCellStyle();
CreationHelper createHelper=wb.getCreationHelper();
cellStyle.setDataFormat(
createHelper.createDataFormat().getFormat(“dd-MM-yyyy”);
SimpleDataFormat sdf=新SimpleDataFormat(“yyyy-MM-dd”);
日期d=空;
试一试{
d=sdf.parse(cell.getStringCellValue());
}捕获(解析异常){
//TODO自动生成的捕捉块
d=零;
e、 printStackTrace();
继续;
}
cell.setCellValue(d);
cell.setCellStyle(cellStyle);
}
file.close();
FileOutputStream outFile=新FileOutputStream(新文件(输出));
工作簿。写入(输出文件);
workbook.close();
outFile.close();
}}

要设置为默认的Excel类型日期(默认为操作系统级别的语言环境/->即xlsx由德国人或英国人打开时会看起来不同/如果您在Excel的单元格格式选择器中选择它,则会用星号标记),您应该:

    CellStyle cellStyle = xssfWorkbook.createCellStyle();
    cellStyle.setDataFormat((short)14);
    cell.setCellStyle(cellStyle);

我用xlsx做的,效果很好。

我在这里写我的答案是因为它可能会对其他读者有所帮助,他们的要求可能与这里的提问者略有不同

我准备了一个.xlsx模板;所有将填充日期的单元格都已格式化为日期单元格(使用Excel)

我使用ApachePOI打开.xlsx模板,然后将日期写入单元格,就可以了

在下面的示例中,单元格A1已从Excel中格式化,格式为
[$-409]mmm-yyyy
,Java代码仅用于填充单元格

FileInputStream inputStream = new FileInputStream(new File("Path to .xlsx template"));
Workbook wb = new XSSFWorkbook(inputStream);
Date date1=new Date();
Sheet xlsMainTable = (Sheet) wb.getSheetAt(0);
Row myRow= CellUtil.getRow(0, xlsMainTable);
CellUtil.getCell(myRow, 0).setCellValue(date1);

打开Excel时,日期的格式正确。

要知道Excel使用的格式字符串而不必猜测它:创建一个Excel文件,在单元格A1中写入一个日期,并根据需要设置格式。然后运行以下行:

FileInputStream fileIn = new FileInputStream("test.xlsx");
Workbook workbook = WorkbookFactory.create(fileIn);
CellStyle cellStyle = workbook.getSheetAt(0).getRow(0).getCell(0).getCellStyle();
String styleString = cellStyle.getDataFormatString();
System.out.println(styleString);
然后复制粘贴结果字符串,删除反斜杠(例如
d/m/yy\h\.mm;@
变成
d/m/yy h.mm;@
),并在代码中使用它:


谢谢忍者,这对我有用。为需要这样做的其他人提供一条评论。有一个名为
BuiltInformation
的POI类,它列出了Excel知道的所有标准格式(不仅仅是日期格式)。我坚持使用其中一个作为上面代码片段中显示的
getFormat()
方法的参数。重要的部分是链接的注释:我们将第二个单元格样式设置为日期(和时间)。从工作簿中创建一个新的单元格样式是很重要的,否则您可能会修改内置样式,不仅影响此单元格,还影响其他单元格。谢谢,@ninja。您知道为什么需要
getCreationHelper()
?我现在正在使用Mule生成一个Excel输出文件,实际上我能够在没有创建助手的情况下使用
createDataFormat()
,并在测试中生成一个Excel文件。不使用它有什么坏处吗?谢谢@Rashiki这个答案是6年前发布的。我猜ApachePOI的API在此期间发生了变化。我对你的问题的回答是‘不,没有负面影响(如果它能按预期工作)’这看起来不错,但它不会将单元格类型设置为“日期”,而是“自定义”。完全同意fiffy的评论。我只有一个问题。最好的方法是什么。依赖数据格式短值(14)或字符串值(“m/d/yy”)。哪个是描述Excel中标准日期格式的常量值?DataFormat.getFormat()同时具有with string和with short value作为参数。Miklos,我不知道string value解决方案是如何工作的。如果有人能给出反馈,我会很高兴,这是否也是一种表现
FileInputStream fileIn = new FileInputStream("test.xlsx");
Workbook workbook = WorkbookFactory.create(fileIn);
CellStyle cellStyle = workbook.getSheetAt(0).getRow(0).getCell(0).getCellStyle();
String styleString = cellStyle.getDataFormatString();
System.out.println(styleString);
CellStyle cellStyle = wb.createCellStyle();
CreationHelper createHelper = wb.getCreationHelper();
cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("d/m/yy h.mm;@"));
cell = row.createCell(1);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);