質問

I'm struggling to work out what this issue is, I have an excel spreadsheet that has to be imported into my SQL Server Database. I iterate through it as follows:

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();

The error I'm getting is

Cannot convert System.DBNull to int

at this line:

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

I have no idea what this error means, and there are no null values in the cells I am accessing. Please advise?

役に立ちましたか?

解決

In at least one of your cells the font size is System.DBNull.

You have to check the type of Size before casting it:

if(Convert.IsDBNull(xlWorksheet.Cells[num, 1].Font.Size))
{
}
else if((int)xlWorksheet.Cells[num, 1].Font.Size == 14)
{
    // do Something....
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top