1

I wrote some code to read cell values from existing excel file.
When I debug, the program throw a "System.Runtime.InteropServices.COMException". I know that we should never use 2 dots with COM objects, but I don't know how to fix my code.
Please help me to clean up COM object when opening excel file.

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);

    }
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
mrJohnt4
  • 33
  • 3
  • 2
    Possible duplicate of [How do I properly clean up Excel interop objects?](http://stackoverflow.com/questions/158706/how-do-i-properly-clean-up-excel-interop-objects) – Ken White Mar 24 '17 at 02:11
  • I already read this post, but I don't know how to fix my code. Please fix my code for me. Thanks a lot – mrJohnt4 Mar 24 '17 at 02:16
  • 1
    *Please fix my code for me* is not a valid question here. Use the code in the linked duplicate, the debugger, and the stack trace from the exception and figure out what's causing it. The code in the linked duplicate shows you precisely how to properly clean up Excel interop code, which is what your question asks. Don't expect us to do everything for you. There are also existing questions here about retrieving the contents of a cell using C#. – Ken White Mar 24 '17 at 02:21

1 Answers1

0

If you are using alpha numeric index use:

string d = xlSheet.UsedRange.Cells["B3"].Value.ToString();

Or to access the cells using the index use

string d = xlSheet.UsedRange.Cells[3, 2].Value.ToString();
Thiru
  • 3,293
  • 7
  • 35
  • 52