Jim*_*ugh 93 java date apache-poi
我已经使用Apache POI一段时间以编程方式读取现有的Excel 2003文件.现在我有了一个新的要求,即在内存中创建整个.xls文件(仍使用Apache POI),然后将它们写入文件末尾.阻碍我的唯一问题是处理带日期的细胞.
请考虑以下代码:
Date myDate = new Date();
HSSFCell myCell;
// code that assigns a cell from an HSSFSheet to 'myCell' would go here...
myCell.setCellValue(myDate);
Run Code Online (Sandbox Code Playgroud)
当我将包含此单元格的工作簿写入文件并使用Excel打开时,单元格显示为数字.是的,我确实认识到Excel将其"日期"存储为自1900年1月1日以来的天数,这就是单元格中的数字所代表的数字.
问题:我可以在POI中使用哪些API调用来告诉它我需要将默认日期格式应用于我的日期单元格?
理想情况下,如果用户在Excel中手动打开电子表格并键入Excel识别为日期的单元格值,我希望电子表格单元格显示的Excel默认日期格式与Excel分配的格式相同.
nin*_*nja 155
http://poi.apache.org/spreadsheet/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);
Run Code Online (Sandbox Code Playgroud)
Blo*_*ode 23
要设置为默认Excel类型日期(默认为操作系统级别区域设置/ - >例如,如果您在Excel的单元格格式选择器中选择,则在德国或英国人打开时xlsx将显示不同/并且标有星号)您应该:
CellStyle cellStyle = xssfWorkbook.createCellStyle();
cellStyle.setDataFormat((short)14);
cell.setCellStyle(cellStyle);
Run Code Online (Sandbox Code Playgroud)
我用xlsx做到了它并且工作正常.
Mr.*_*Joe 12
此示例适用于.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);
Run Code Online (Sandbox Code Playgroud)
除了 @BlondeCode答案之外,这里还列出了您可以获得的所有可用格式
creationHelper.createDataFormat().getFormat((short) index)
0 = “常规”
1 = “0”
2 = “0.00”
3 = “#,##0”
4 = “#,##0.00”
5 = “”$”#,##0_);(“$” #,##0)"
6 = ""$"#,##0_);红色"
7 = ""$"#,##0.00_);("$"#,##0.00)"
8 = " "$"#,##0.00_);红色"
9 = "0%"
10 = "0.00%"
11 = "0.00E+00"
12 = "# ?/?"
13 =“#??/??”
14 =“月/日/年”
15 =“日-毫米-年”
16 =“日-毫米”
17 =“毫米-年”
18 =“小时:分钟上午/下午”
19 =“小时:毫米:秒” AM/PM"
20 = "h:mm"
21 = "h:mm:ss"
22 = "m/d/yy h:mm"
23-36 = 保留
37 = "#,##0_);(#, ##0)"
38 = "#,##0_);红色"
39 = "#,##0.00_);(#,##0.00)"
40 = "#,##0.00_);红色"
41 = " (* #,##0 ); (* (#,##0); (* "-" ); (@ )"
42 = " ("$"* #,##0_); ("$ "* (#,##0); ("$"* "-" ); (@ )"
43 = " (* #,##0.00_); (* (#,##0.00); (* " -"?? ); (@ )"
44 = " ("$"* #,##0.00_); ("$"* (#,##0.00); ("$"* "-"?? ) ; (@_)"
45 = "mm:ss"
46 = "[h]:mm:ss"
47 = "mm:ss.0"
48 = "##0.0E+0"
49 = "@"
从索引 164 开始,有您的自定义模式