java 使用 POI 应用特定的单元格数据格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10892204/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Applying specific cell data format using POI
提问by markiz
I need to apply specific data format to cell.
我需要将特定的数据格式应用于单元格。
XSSFCellStyle cellStyle = workBook.createCellStyle();
XSSFDataFormat format = workBook.createDataFormat();
cellStyle.setDataFormat(format.getFormat("m/d/yy h:mm"));
dataCell.setCellType(1); //String
dataCell.setCellStyle(cellStyle);
The data is being written but the problem is that the format is applied onlywhen I open excel sheet (in Excel application), click inside the cell with my data.
And then pressing Enter key.
Only then the format is applied.
正在写入数据,但问题是该格式仅在我打开 Excel 工作表(在 Excel 应用程序中)时应用,在包含我的数据的单元格内单击。
然后按回车键。只有这样才能应用格式。
How can I apply the format without clicking on every cell?
如何在不单击每个单元格的情况下应用格式?
回答by Gagravarr
Your problem is that you're setting the cell to be a string. For the most part, cell formatting rules only apply to numeric cells. They don't apply to string cells, those don't get formatted (as they're already formatted to a string!)
您的问题是您将单元格设置为字符串。大多数情况下,单元格格式规则仅适用于数字单元格。它们不适用于字符串单元格,它们不会被格式化(因为它们已经被格式化为字符串!)
XSSFCellStyle cellStyle = workBook.createCellStyle();
XSSFDataFormat format = workBook.createDataFormat();
cellStyle.setDataFormat(format.getFormat("m/d/yy h:mm"));
dataCell.setCellStyle(cellStyle);
// Set Cell Type not really needed, the setCellValue does it
dataCell.setCellType(Cell.CELL_TYPE_NUMERIC);
// Set a date value (2012-06-05 08:50)
dataCell.setCellValue(new Date(1338878999635));
When you open that in Excel, it ought to be have as expected
当你在 Excel 中打开它时,它应该是预期的
回答by Dinesh Ranjeew Silva
This is how you change the cell format to Date
.
这就是将单元格格式更改为Date
.
var workBook = new XSSFWorkbook();
var sheet = workBook.CreateSheet("Sheet1");
var dateStyle = workBook.CreateCellStyle();
var dataFormat = workBook.CreateDataFormat();
dateStyle.DataFormat = dataFormat.GetFormat("M/D/YYYY");
row.CreateCell(0).SetCellValue(item.ModifiedDate.HasValue ?
item.ModifiedDate.Value.ToShortDateString(): "");
row.Cells[0].CellStyle = dateStyle; // This will change your cell to date
format.