我试图从Excel文件中读取一行 出于某种原因,当我尝试读取整数值(ID列)时出现错误。
代码的作用是从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 :(得分: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;
}