0

I've got this set of code, now, I know you have to dispose com references and run the garbage collector after accessing excel, but my particular code doesn't write excel references to variables... how do I dispose the excel app properly in this case?

Here it is:

                try
            {
                OleDbcon =
                    new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + openFileDialog.FileName +
                                        ";Extended Properties='Excel 8.0; HDR = Yes; IMEX = 1'");
                OleDbcon.Open();
                System.Data.DataTable dt = OleDbcon.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                OleDbcon.Close();
                CMBsheets.Items.Clear();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    String sheetName = dt.Rows[i]["TABLE_NAME"].ToString();
                    sheetName = sheetName.Substring(0, sheetName.Length - 1);
                    CMBsheets.Items.Add(sheetName);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Write Excel: " + ex.Message);
            }

This works but EXCEL doesn't close! so I cannot save data from another codeblock. (Btw, the code adds the excel book into a combobox where the sheets are individually searchable, on selection, the data is displayed into a datagridview)

Thanks in advance!

Avan
  • 223
  • 3
  • 13
  • the best way is to use the object in a using statement, however, I would strongly recommend that you look at ClosedXML. This is far easier to work with. Take a look here https://closedxml.codeplex.com/ – Simon Price Nov 24 '16 at 07:26
  • I tested your code and in my case Excel.exe isn't opened at all. But I guess that's just because the OleDb provider doesn't need Excel.exe to read the contents of the Excel file. Do you perhaps have any other direct COM references in the rest of your code? – haindl Nov 25 '16 at 14:59
  • @haindl Huh, I'll have to do a double take. – Avan Nov 28 '16 at 00:43

0 Answers0