2014-01-17 79 views
0

我正在努力解决这个问题,我有一个必须导入到SQL Server数据库的Excel电子表格。我遍历它如下:无法将System.DBNull转换为int

Microsoft.Office.Interop.Excel.Range xlRange = xlWorksheet.Range["A1", "D6867"]; 

int num = 4; 
// String test = ""; 
foreach (Microsoft.Office.Interop.Excel.Range row in xlRange.Rows) 
{ 
    if ((int)xlWorksheet.Cells[num, 1].Font.Size == 14) 
    { 
      ProductCategory category = new ProductCategory(); 
      category.Category = xlWorksheet.Cells[num, 1].Value.ToString(); 
      db.ProductCategories.Add(category); 
    } 
    num++; 
    //System.Diagnostics.Debug.WriteLine(test); 
} db.SaveChanges(); 
xlWorkbook.Close(true, Missing.Value, Missing.Value); 
xlApp.Quit(); 

我得到的错误是

无法转换System.DBNull为int

在这一行:

if ((int)xlWorksheet.Cells[num, 1].Font.Size == 14) 

我不知道这个错误是什么意思,并且我正在访问的单元中没有空值。请指教?

回答

3

至少有一个单元格的字体大小是System.DBNull。

你有铸造之前检查大小类型:

if(Convert.IsDBNull(xlWorksheet.Cells[num, 1].Font.Size)) 
{ 
} 
else if((int)xlWorksheet.Cells[num, 1].Font.Size == 14) 
{ 
    // do Something.... 
} 
+3

还有Convert.IsDBNull这确实有点超过'is' –

+0

感谢您的提示ta.speot.is,更新了我的答案 – David