0

嗨,我不断从下面的代码中收到此错误,想知道是否有人可以提供帮助。

error processing excel file: cannot perform runtime binding on a null reference

代码:

    private void Import_Click(object sender, RoutedEventArgs e)
    {
        Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();

        // Show open file dialog box
        Nullable<bool> result = dlg.ShowDialog();

        // Process open file dialog box results
        if (result == true)
        {
            // Open document
            string filename = dlg.FileName;

            Microsoft.Office.Interop.Excel.Application vExcelObj = new Microsoft.Office.Interop.Excel.Application();
            try
            {
                Microsoft.Office.Interop.Excel.Workbook theWorkbook = vExcelObj.Workbooks.Open(filename, Type.Missing, true);

                Microsoft.Office.Interop.Excel.Worksheet sheet = theWorkbook.Worksheets[1];  

                string vFirstName = "temp";
                string vLastName = "temp";
                int vIndex = 1;

                while (vFirstName != "")
                {
                    // Change the letters of the appropriate columns here!  
                    // In my example, 'A' is first name, 'B' last name
                    vFirstName = sheet.get_Range("A" + vIndex.ToString()).Value.ToString(); // if i take out the exception handling the error is on this line
                    vLastName = sheet.get_Range("B" + vIndex.ToString()).Value.ToString();


                    this.SaveNewCustomer(vFirstName, vLastName); 

                    vIndex++;

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error processing excel file : " + ex.Message);
            }
            finally
            {
                vExcelObj.Quit();
            }
        }
    }

    private void SaveNewCustomer(string firstName, string lastName) 
    {
        string uri = "http://localhost:8002/Service/Customer";
        StringBuilder sb = new StringBuilder();
        sb.Append("<Customers>");
        sb.AppendLine("<FirstName>" + firstName + "</FirstName>");
        sb.AppendLine("<LastName>" + lastName + "</LastName>");
        sb.AppendLine("</Customers>");
        string NewStudent = sb.ToString();
        byte[] arr = Encoding.UTF8.GetBytes(NewStudent);
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
        req.Method = "POST";
        req.ContentType = "application/xml";
        req.ContentLength = arr.Length;
        Stream reqStrm = req.GetRequestStream();
        reqStrm.Write(arr, 0, arr.Length);
        reqStrm.Close();
        HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
        reqStrm.Close();
        resp.Close();
    }

}

该代码只需要一个 excel 文档并尝试将数据发送到我的 Web 服务。

所以我尝试使用以下方法,但它冻结了应用程序:S 没有错误只是挂起。 编辑尝试:

                while (vFirstName != "")
                {
                        var columnACell = sheet.get_Range("A" + vIndex.ToString());
                        var columnBCell = sheet.get_Range("B" + vIndex.ToString());
                        var columnACellValue = columnACell.Value;
                        var columnBCellValue = columnBCell.Value;


                    if (columnACellValue != null && columnBCellValue != null)
                    {
                        vFirstName = columnACellValue.ToString();
                        vLastName = columnBCellValue.ToString();

                        this.SaveNewStaff(vFirstName, vLastName); //, vPassword

                        vIndex++;
                    }
                }
            }

在此处输入图像描述

4

3 回答 3

3

编辑 2

只是拿了代码,然后逐步完成。发现了问题。我想我误解了最初发生的事情。

发生的事情是循环while (vFirstName != "")将继续进行,直到vFirstName是一个空字符串。但这永远不会发生!原因如下:

  • 只要 A 列和 B 列有值,一切都会好起来的。代码将按预期运行。
  • 当代码到达没有值的 Excel 行时,它会命中一个空单元格,该单元格将.Value设置为null. 这会导致异常。

所以这里真正的解决方案是让循环继续运行,直到它到达一个有null值的单元格,然后退出。有点像这样:

while (true) {
    // Split the satements 
    var columnACell = sheet.get_Range("A" + vIndex.ToString());
    var columnBCell = sheet.get_Range("B" + vIndex.ToString());
    var columnACellValue = columnACell.Value;
    var columnBCellValue = columnBCell.Value;

    if (columnACellValue != null && columnBCellValue != null) {
        vFirstName = columnACellValue.ToString();
        vLastName = columnBCellValue.ToString();

    } else {
        break;
    }

    this.SaveNewCustomer(vFirstName, vLastName);

    vIndex++;

};

刚刚在我身上测试了这个,它似乎有效。

另请注意,确保您完全退出 Excel,因为调用Excel.Quit()通常是不够的。打开任务管理器并检查是否有任何额外的 EXCEL.exe 实例浮动。为了防止这些,我通常在完成 Excel 后将其杀死(比正确释放 Excel 的 COM 对象更容易),如本文所述。


原帖

听起来这里有几个选项:

  • 单元格是空的,这意味着.Value它将是null.
  • sheetnull,_
  • get_Range()返回null——这听起来不太可能。

将该行拆分为单独的语句,看看其中哪一个会引发错误。这将告诉你在哪里进一步寻找。

从你在做什么来判断——搜索列直到找到名字——听起来你在单元格中遇到了空值Value。为了解决这个问题,我通常会添加一个快速的 if 语句来测试Value.null

编辑

这是一个示例(可能无法编译),有望修复null单元格内的值并帮助查明其他null相关问题。用这样的东西替换有问题的行:

var columnACell = sheet.get_Range("A" + vIndex.ToString());
var columnBCell = sheet.get_Range("B" + vIndex.ToString())
var columnACellValue = columnACell.Value;
var columnBCellValue = columnBCell.Value;

if (columnACellValue != null && columnBCellValue != null) {
    vFirstName = columnACellValue.ToString(); 
    vLastName = columnBCellValue.ToString();
}

请注意,我假设您的 C# 编译器通过var.

于 2012-07-24T20:20:23.723 回答
0

工作表为空。也许只有 1 个工作表?您正在使用 Worksheets[1] 返回第二个,当然.. :)

于 2012-07-24T20:17:45.700 回答
0

尝试拆分读取该值的代码并测试它是否为空。

object oName = sheet.get_Range("A" + vIndex.ToString()).Value;
vFirstName = (oName == null ? string.Empty : oName.ToString();
object oLast = sheet.get_Range("B" + vIndex.ToString()).Value;
vLastName = (oLast == null ? string.Empty : oLast.ToString());
if(vFirstName.Length > 0 && vLastName.Length > 0)
     this.SaveNewCustomer(vFirstName, vLastName);   

并注意到在您的 SaveNewStaff/Customer(....) 中您关闭了 RequestStream 两次。也许第二次关闭会冻结您的代码。

    reqStrm.Close();  
    HttpWebResponse resp = (HttpWebResponse)req.GetResponse();  
    reqStrm.Close();  // <= Already closed before?
于 2012-07-24T20:28:55.210 回答