我有下面的代码从Excel文件中读取数据,我遇到的是,当我尝试读取范围内的数据,我得到一个问题除了在这条线读取数据从Excel电子表格 - 无法执行运行时的空引用结合
if (Int32.TryParse(xlRange.Cells[1, 4].Value2.ToString(), out value))
“不能执行运行时对空引用结合”我想知道的是我如何进入该范围内的信息正确,请。在此先感谢
void ReadFromExcelToGrid2(String fileNameString)
{
try
{
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(fileNameString);
//get list of worksheets associated with the current workbook
Microsoft.Office.Interop.Excel.Sheets worksheets = xlWorkbook.Worksheets;
//list the work books in a dropdownlist
IDictionary<int, String> sheets = new Dictionary<int, String>();
foreach (Microsoft.Office.Interop.Excel.Worksheet displayWorksheet in xlWorkbook.Worksheets)
{
sheets.Add(displayWorksheet.Index, displayWorksheet.Name);
}
cmbWorksheets.DataSource = new BindingSource(sheets, null);;
cmbWorksheets.DisplayMember = "Value";
cmbWorksheets.ValueMember = "Key";
Microsoft.Office.Interop.Excel.Worksheet xlWorksheet = xlWorkbook.Sheets[4]; // assume it is the first sheet
Microsoft.Office.Interop.Excel.Range xlRange = xlWorksheet.UsedRange; // get the entire used range
int value = 0;
if (Int32.TryParse(xlRange.Cells[1, 4].Value2.ToString(), out value)) // get the F cell from the first row
{
int numberOfColumnsToRead = value * 4;
for (int col = 7; col < (numberOfColumnsToRead + 7); col++)
{
Console.WriteLine(xlRange.Cells[1, col].Value2.ToString()); // do whatever with value
}
}
}
catch (Exception ex)
{
throw ex;
}
}
细胞[]是基于一个,而不是从零开始 – 2012-07-21 16:13:18
这是我的错误。我改变了测试的数字,但忘记改回它。是的,问题依然存在。 – Kobojunkie 2012-07-21 16:33:33