从ExcelSheetparsingDateTime

我正在寻找一些build议。

我正在写一个类来自动从Excel电子表格(使用NPOI api)中提取信息,然后将这些信息导入到数据库中。 除了一个小问题之外,我已经可以正常工作了。

我正在使用的电子表格之一包含以下格式的date: 04/01/2011 04:43:28

当我运行Web应用程序时,出现以下错误消息:

string未被识别为有效的date时间

所以我在这之后通过代码进行debugging,结果是date被读入: 40546.0151388889 ,所以它被格式化回一个数字。

我不确定如何解决这个问题,我希望有人能指出我正确的方向?

这里是我的代码exerpt:

using (FileStream fs = File.Open(filename, FileMode.Open, FileAccess.Read)) { HSSFWorkbook templateWorkbook = new HSSFWorkbook(fs); HSSFSheet sheet = templateWorkbook.GetSheetAt(w); HSSFRow row = null; for (int i = 1; i <= sheet.LastRowNum; i++) { FTPSalesDetails t = null; int currentColumn = 0; try { ModelContainer ctn = new ModelContainer(); row = sheet.GetRow(i); if (row == null) { continue; } t = new FTPSalesDetails { RowNumber = i, InvoiceDate = GetCellValue(row.GetCell(0)), NetUnitsSold = GetCellValue(row.GetCell(2)), ProductCode = GetCellValue(row.GetCell(5)) }; int Qty = int.Parse(t.NetUnitsSold); // Do a Loop for net units sold. for (int x = 0; x < Qty; x++) { ItemSale ts = new ItemSale { ItemID = GetItemID(t.ProductCode), RetailerID = GetRetailerID("Samsung"), DateSold = DateTime.Parse(t.InvoiceDate), }; ctn.AddToItemSales(ts); ctn.SaveChanges(); } } .... private string GetCellValue(HSSFCell cell) { string ret = null; if (cell == null) { return ret; } switch (cell.CellType) { case HSSFCell.CELL_TYPE_BOOLEAN: ret = cell.BooleanCellValue.ToString(); break; case HSSFCell.CELL_TYPE_NUMERIC: ret = cell.NumericCellValue.ToString(); break; case HSSFCell.CELL_TYPE_STRING: ret = cell.StringCellValue; break; } return ret; } 

使用DateTime.FromOADate(cellValue)

(你可能需要做的(cellValue – 1),因为Exceldate计算中的错误)

当您尝试从Excel中提取date时,将其转换为特定的格式。将此值加倍并使用它,如下所示。

尝试:

 double dateDouble = 40546.0151388889 DateTime dt = DateTime.FromOADate(dateDouble); string dateString = dt.ToString(); 

看到这个优秀的阅读date和Excel的:

Excel将date和时间存储为表示自1900年1月1日以来的天数加上24小时日的小数部分的数字:
ddddd.tttttt。 这被称为序列date或序列date时间。

在这里find这个链接。 稍微修改了我自己的解决scheme的代码,但它完美的作品。 感谢所有的答复。