Why does Microsoft.Office.Interop.Excel.Applicatio

2019-01-09 12:47发布

The following code leaves a Microsoft Excel background process running, until after my program has exited:

var excelApplication = new Application();
var workbooks = excelApplication.Workbooks;
var workbook = excelApplication.Workbooks.Open(file.FullName);

workbook.Close();
excelApplication.Workbooks.Close();
excelApplication.Quit();

Marshal.ReleaseComObject(workbook);
Marshal.ReleaseComObject(workbooks);
Marshal.ReleaseComObject(excelApplication);

Why? What am I missing?

3条回答
太酷不给撩
2楼-- · 2019-01-09 13:08

Got it!

application.Workbooks != application.Workbooks

This property doesn't expose a variable, it generates a value. So every time I access the Workbooks property I create a new COM object.

I fixed the code and all is well. Thanks, everybody.

var excelApplication = new Application();
var workbooks = excelApplication.Workbooks;
var workbook = workbooks.Open(pathToExcelWorkbook); // Fixed

workbook.Close();
workbooks.Close();
excelApplication.Quit();

Marshal.ReleaseComObject(workbook);
Marshal.ReleaseComObject(workbooks);
Marshal.ReleaseComObject(excelApplication);
查看更多
手持菜刀,她持情操
3楼-- · 2019-01-09 13:15

THIS IS WRONG WAY TO DO LIKE THIS, but this is most easy way to fix the issue:

    [DllImport("user32.dll")]
    private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);

    private Application _excelApp;
    private Workbook _excelWorkBook;
    private Worksheet _excelSheet;

    private void CloseExcelApp()
    {
        int hWnd = _excelApp.Application.Hwnd;
        uint processID;

        GetWindowThreadProcessId((IntPtr)hWnd, out processID);
        Process.GetProcessById((int)processID).Kill();

        _excelWorkBook = null;
        _excelApp = null;
        _excelSheet = null;
    }

all you need is to init all uninitialized variables when you need to work with it, and call CloseExcelApp() when you need to close app.

查看更多
来,给爷笑一个
4楼-- · 2019-01-09 13:17

This is a widely-spread issue with Office applications. All Excel add-ins/automation applications should systematically release their references to Excel objects when they are no longer needed. Failing to systematically release reference to Excel objects can prevent Microsoft Office Excel from shutting down properly. See Systematically Releasing Objects for more information. It is related to Outlook, but the same principles can be applied to all Office applications.

Use System.Runtime.InteropServices.Marshal.ReleaseComObject to release an Excel object when you have finished using it. Then set a variable to Nothing in Visual Basic (null in C#) to release the reference to the object.

查看更多
登录 后发表回答