无法将System.DBNull转换为int
我正在努力解决这个问题,我有一个Excel电子表格必须导入到我的SQL Server数据库。 我遍历它如下:
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)
我不知道这个错误是什么意思,并且我正在访问的单元格中没有空值。 请指教?
至less在其中一个单元中,字体大小为System.DBNull。
投掷前必须检查大小的types:
if(Convert.IsDBNull(xlWorksheet.Cells[num, 1].Font.Size)) { } else if((int)xlWorksheet.Cells[num, 1].Font.Size == 14) { // do Something.... }