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();
}
}
您的Excel文件中是否有任何空的** ID **列?它看起來像你試圖將一個空的單元格值轉換爲int –
否如果你不相信我(: – user200544
值是否從excel表格到範圍對象? –