2

我有下面的代码来从 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;
            }
            }
4

2 回答 2

7
if (xlRange.Cells[row, 1].Text == "")
{
    xlRange.Cells[row, 1].value = "Blank";
}

上面的代码将解决这个问题。但是Blank不会在牢房里。但它会让你更进一步。基本上 C#/Excel 不喜欢null.

于 2012-09-04T17:05:03.107 回答
1

如果您使用“ Convert.ToString() ”而不是“ .ToString() ”怎么办?如果“xlRange.Cells[1, 4].Value2”为空,那么它将没有 .ToString() 函数,如果我的想法正确,应该抛出异常。Convert.ToString() 和 .ToString() 之间的区别在于 Convert.ToString () 将返回一个空值,而 .ToString() 将爆炸。

您能否在该代码执行之前设置一个断点以确保 xlRange 实际上包含其中的信息?

于 2012-07-21T17:38:43.557 回答