POI - 我如何单元格的值设置为日期和应用默认的Excel日期格式? [英] POI - How do I set cell value to Date and apply default Excel date format?

查看:2530
本文介绍了POI - 我如何单元格的值设置为日期和应用默认的Excel日期格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用Apache POI一段时间以编程方式读取现有的Excel 2003文件。现在我有一个新的要求,在内存中创建整个.xls文件(仍在使用Apache POI),然后将它们写入结尾的文件。站在我的路,唯一的问题是日期的单元格的处理。

I've been using Apache POI for some time to read existing Excel 2003 files programmatically. Now I have a new requirement to create entire .xls files in-memory (still using Apache POI) and then write them to a file at the end. The only problem standing in my way is the handling of cells with dates.

考虑以下code:

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日,这是什么在小区重presents数量。

When I write the workbook containing this cell out to a file and open it with Excel, the cell is displayed as a number. Yes, I do realize that Excel stores its 'dates' as the number of days since January 1 1900 and that is what the number in the cell represents.

问:我可以在POI使用什么API调用来告诉它,我想应用到我的日期单元格默认的日期格式

理想我想与Excel的会赋予它如果用户手动打开了在Excel在S preadsheet和类型在单元格中值相同的默认日期格式所显示的s preadsheet细胞的Excel识别为一个日期

Ideally I want the spreadsheet cell to be displayed with the same default date format that Excel would have assigned it if a user had manually opened the spreadsheet in Excel and typed in a cell value that Excel recognized as being a date.

推荐答案

<一个href=\"http://poi.apache.org/s$p$padsheet/quick-guide.html#CreateDateCells\">http://poi.apache.org/s$p$padsheet/quick-guide.html#CreateDateCells

CellStyle cellStyle = wb.createCellStyle();
CreationHelper createHelper = wb.getCreationHelper();
cellStyle.setDataFormat(
    createHelper.createDataFormat().getFormat("m/d/yy h:mm"));
cell = row.createCell(1);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);

这篇关于POI - 我如何单元格的值设置为日期和应用默认的Excel日期格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆