Closing an Excel Workbook

griegs picture griegs · Jul 3, 2013 · Viewed 17.5k times · Source

I have a bit of code that opens an xls workbook;

Excel.Workbooks workBooks;
workBooks = excelApp.Workbooks;
workbook = workBooks.Open(sourceFilePath + sourceFileName + ".xls");

I then get the work sheet;

worksheets = workbook.Worksheets;
worksheet = worksheets.get_Item("Standard");

I then save the file as a csv;

worksheet.SaveAs(sourceFilePath + sourceFileName + ".csv", Excel.XlFileFormat.xlCSVWindows, Type.Missing, Type.Missing, false, false, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing);

Then I try to close the workbook;

Marshal.FinalReleaseComObject(worksheet);
Marshal.FinalReleaseComObject(worksheets);
workbook.Close();
Marshal.FinalReleaseComObject(workbook);

However, every time i get to the line workbook.Close(), the system stops.

If I do not do the SaveAs then the workbook closes just fine.

How do I close a workbook?

edit

Looking at Task Manager shows me that Excel.exe is still running. Closing it will produce an error in my code.

edit 2

I have already seen the referenced SO post and it did not solve the issue.

Answer

Hercules picture Hercules · Jul 3, 2013

Here is the solution

first: using EXCEL = Microsoft.Office.Interop.Excel;

and then, path is where your excel locates.

        EXCEL.Application excel = new EXCEL.Application();
        try
        {
            EXCEL.Workbook book = excel.Application.Workbooks.Open(path);
            EXCEL.Worksheet sheet = book.Worksheets[1];
            // yout operation

        }
        catch (Exception ex) { MessageBox.Show("readExcel:" + ex.Message); }
        finally
        {
            KillExcel(excel);
            System.Threading.Thread.Sleep(100);
        }



    [DllImport("User32.dll")]
    public static extern int GetWindowThreadProcessId(IntPtr hWnd, out int ProcessId);
    private static void KillExcel(EXCEL.Application theApp)
    {
        int id = 0;
        IntPtr intptr = new IntPtr(theApp.Hwnd);
        System.Diagnostics.Process p = null;
        try
        {
            GetWindowThreadProcessId(intptr, out id);
            p = System.Diagnostics.Process.GetProcessById(id);
            if (p != null)
            {
                p.Kill();
                p.Dispose();
            }
        }
        catch (Exception ex)
        {
            System.Windows.Forms.MessageBox.Show("KillExcel:" + ex.Message);
        }
    }