2017-04-22 172 views
0

我想從Excel文件讀取一行。
由於某些原因,當我嘗試讀取整數值(ID列)時出現錯誤。從excel文件讀取錯誤

代碼的功能是從Excel文件 中讀取信息並隨後進行存儲。

UserInfo實現爲數組。
(Excel File Image)

它拋出這個錯誤:ErrorImage

class UserInfo 
    { 
      public int ID { get; set; } 
      public string firstName { get; set; } 
      public string lastName { get; set; } 
      public string IDNumber { get; set; } 
      public string email { get; set; } 
    } 


    private void openExcelFile(string excelFile) 
    { 
     UserInfo[] user = new UserInfo[2]; 
     label1.Text += "Initalize Excel Application And Reading Data"; 
     ///Read From Excel File And Store in array 
     Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application(); 
     Workbook xlWorkbook = xlApp.Workbooks.Open(excelFile); 
     _Worksheet xlWorksheet = xlWorkbook.Sheets[1]; 
     Range xlRange = xlWorksheet.UsedRange; 
     int rowCount = xlRange.Rows.Count; 
     //Start to read from row 2 
     for (int i = 2; i <= rowCount; i++) 
     { 
      user[i - 2] = new UserInfo(); 
      Range range1 = xlWorksheet.Rows[i]; 
      user[i - 2].firstName = range1.Cells[i, 1].Value2; 
      user[i - 2].lastName = range1.Cells[i, 2].Value2; 
      user[i - 2].ID = range1.Cells[i, 3].Value2; //Error 
      user[i - 2].email = range1.Cells[i, 4].Value2; 
     } 

     label1.Text += "Done!\nStart Sql Process:\n"; 
     //Cleaning GC,Dealing memory 
     GC.Collect(); 
     GC.WaitForPendingFinalizers(); 
     //close and release 
     xlWorkbook.Close(); 
     Marshal.ReleaseComObject(xlWorkbook); 
     //quit and release 
     xlApp.Quit(); 
    } 
} 
+0

您的Excel文件中是否有任何空的** ID **列?它看起來像你試圖將一個空的單元格值轉換爲int –

+0

否如果你不相信我(: – user200544

+0

值是否從excel表格到範圍對象? –

回答

0

我遇到過是它可能是特定的單元格的數據類型的錯誤不是INT所以它不能轉換的,該數據單元格爲int。 您可以嘗試使用下面的示例作爲解決方法:

Range r = activeWorksheet.get_Range("A3","F3"); 
int d; 
if (r.Cells[3, 5].Value2 != null) 
{ 
    var c = r.Cells[3, 5].Value2.ToString(); 
    d = Convert.ToInt32(c); 
} 
else 
{ 
    d = 0; 
}