0

I have the following piece of code to format the excel files that I get and save them as modified.xlsx

public void FormatFile()
{  
FileName = Convert.ToString("test.xlsx");
            SourceFileLocation = ("C:\Test");

            SourceFileName = Path.Combine(SourceFileLocation, FileName);
            saveLoc = Path.Combine(SourceFileLocation, "ModifiedExcel.xlsx");


            var excel = new Excel.Application();
            var workbook = excel.Workbooks.Open(SourceFileName);
            //var sheet = (Excel.Worksheet)workbook.Worksheets.Item[1]; // 1 is the first item, this is NOT a zero-based collection
            try
            {
                foreach (Excel.Worksheet tempSheet in workbook.Worksheets)
                {
                    if (((Excel.Worksheet)(tempSheet)).Name.Contains("Sheet1"))
                    {
                        if (File.Exists(saveLoc))
                        {
                            File.Delete(saveLoc);
                        }
                        tempSheet.Select();
                        workbook.SaveAs(saveLoc);
                    }

                    System.Runtime.InteropServices.Marshal.ReleaseComObject(tempSheet);
                }

                workbook.Save();
                workbook.Close();
                excel.Quit();

                System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
            }
            catch(Exception)
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
            }

I release the excel objects but when I check my task manager I can still see excel processes running. If i have run this code multiple time, that many processes are created. Am I not releasing the excel objects correctly?

perplexedDev
  • 857
  • 4
  • 17
  • 49
  • This was asked a few days ago. Can't find it now though. – findwindow Apr 22 '16 at 22:38
  • Nearly every `.` creates a new COM object that you have to release. `excel.Workbooks.Open()` creates a `Workbooks` object, so you need to create a `Workbooks` object and set `myWorkbooksObject = excel.Workbooks`, then you can release it as you have a reference to it. – Quantic Apr 22 '16 at 22:38
  • 2
    http://stackoverflow.com/questions/158706/how-to-properly-clean-up-excel-interop-objects – David Oesterreich Apr 22 '16 at 22:43
  • Also you need to assign `workbook.Worksheets` to a `Worksheets` object and clean that too. So I think there's 4 objects: `Application`, `Workbooks`, `Workbook`, `Worksheets`, `Worksheet`. After running `ReleaseComobject(theObject)`, also set `theObject = null` so the garbage collector knows it can release the resources soon. – Quantic Apr 22 '16 at 22:47

0 Answers0