Excel interop COM doesn't close

前端 未结 4 628
青春惊慌失措
青春惊慌失措 2021-01-22 03:27

I have some code that opens a spreadsheet, reads some values, and then closes the sheet. I need to do this for multiple files. The problem I\'m having is that the Excel applic

4条回答
  •  无人共我
    2021-01-22 04:11

    Ended up killing the processes, that was the only thing that worked.

        [DllImport("user32.dll")]
        private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
    
        ///  Tries to find and kill process by hWnd to the main window of the process.
        /// Handle to the main window of the process.
        /// True if process was found and killed. False if process was not found by hWnd or if it could not be killed.
        public static bool TryKillProcessByMainWindowHwnd(int hWnd)
        {
            uint processID;
            GetWindowThreadProcessId((IntPtr)hWnd, out processID);
            if (processID == 0) return false;
            try
            {
                Process.GetProcessById((int)processID).Kill();
            }
            catch (ArgumentException)
            {
                return false;
            }
            catch (Exception ex)
            {
                return false;
            }            
            return true;
        }
    
        static void ParseFile(string file)
        {
            try
            {
                log("parsing:" + file);
                Excel.Application excel = new Excel.Application();
                Excel.Workbook wb = excel.Workbooks.Open(file);
                Excel.Worksheet ws = wb.Worksheets[1];
                //do some stuff here
                wb.Close(false);
                int hWnd = excel.Application.Hwnd;
                excel.Quit();
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
                Marshal.FinalReleaseComObject(ws);
                Marshal.FinalReleaseComObject(wb);
                Marshal.FinalReleaseComObject(excel);                
                excel = null;
                ws = null;
                wb = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
                TryKillProcessByMainWindowHwnd(hWnd);
            }
            catch (Exception ex)
            {
                log(ex.Message);
            }            
        }
    

提交回复
热议问题