我有下面的代碼從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