Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在打开excel文件时清理COM对象_C#_Winforms - Fatal编程技术网

C# 如何在打开excel文件时清理COM对象

C# 如何在打开excel文件时清理COM对象,c#,winforms,C#,Winforms,我编写了一些代码从现有的excel文件中读取单元格值调试时,程序抛出“System.Runtime.InteropServices.COMException”。我知道我们不应该在COM对象中使用2个点,但我不知道如何修复我的代码请帮助我在打开excel文件时清理COM对象 private void button1_Click(object sender, EventArgs e) { Excel.Application xlApp = new Excel.Applicat

我编写了一些代码从现有的excel文件中读取单元格值
调试时,程序抛出“System.Runtime.InteropServices.COMException”。我知道我们不应该在COM对象中使用2个点,但我不知道如何修复我的代码
请帮助我在打开excel文件时清理COM对象

private void button1_Click(object sender, EventArgs e)
    {
        Excel.Application xlApp = new Excel.Application();
        Excel.Workbook xlBook;
        Excel.Worksheet xlSheet;

        xlBook = xlApp.Workbooks.Open(@"C:\Users\trump45\Desktop\trump45.xls");
        xlApp.Visible = false;

        xlSheet = xlBook.Sheets["Sheet4"];

        //Exception rising here            
        string d = xlSheet.UsedRange.Cells[3, "B"].Value.ToString();

        MessageBox.Show(d);

        xlBook.Close(false, Missing.Value, Missing.Value);
        xlApp.Quit();

        System.Runtime.InteropServices.Marshal.ReleaseComObject(xlSheet);
        System.Runtime.InteropServices.Marshal.ReleaseComObject(xlBook);
        System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);

    }

如果使用字母数字索引,请使用:

string d = xlSheet.UsedRange.Cells["B3"].Value.ToString();
或者使用索引访问单元格

string d = xlSheet.UsedRange.Cells[3, 2].Value.ToString();

如果使用字母数字索引,请使用:

string d = xlSheet.UsedRange.Cells["B3"].Value.ToString();
或者使用索引访问单元格

string d = xlSheet.UsedRange.Cells[3, 2].Value.ToString();

我可能已经读过这篇文章,但我不知道如何修复我的代码。请帮我修改代码。谢谢,请为我修复我的代码在这里不是一个有效的问题。使用链接副本、调试器和异常的堆栈跟踪中的代码,找出导致异常的原因。链接副本中的代码准确地向您展示了如何正确清理Excel互操作代码,这就是您的问题所在。别指望我们为你做任何事。关于使用C#检索单元格内容,这里也存在一些问题。我可能已经读过这篇文章,但我不知道如何修复我的代码。请帮我修改代码。谢谢,请为我修复我的代码在这里不是一个有效的问题。使用链接副本、调试器和异常的堆栈跟踪中的代码,找出导致异常的原因。链接副本中的代码准确地向您展示了如何正确清理Excel互操作代码,这就是您的问题所在。别指望我们为你做任何事。关于使用C#检索单元格内容,这里还存在一些问题。