109*_*793 2 c# asp.net excel datetime
我正在寻找一些建议.
我正在编写一个类来自动从C#中的excel电子表格(使用NPOI api)中提取信息,然后将此信息导入数据库.除了一个小问题,我已经完成了所有工作.
我正在使用的其中一个电子表格包含以下格式的日期:04/01/2011 04:43:28.
当我运行Web应用程序时,我收到以下错误消息:
字符串未被识别为有效的DateTime
所以我在此之后通过代码进行了调试,事实证明日期正在读入: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;
}
Run Code Online (Sandbox Code Playgroud)
使用DateTime.FromOADate(cellValue)
(由于excel日期计算中的错误,您可能需要执行(cellValue - 1))