Excel interop COM doesn't close

前端 未结 4 623
青春惊慌失措
青春惊慌失措 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:12

    1. Use Marshal.FinalReleaseComObject() to release the resources

    2. If you read multiple files one after the other then performance wise it is much better to open/close Excel Application only once and move the open/close application part to separate functions

    Refactored Code:

    static Excel.Application OpenExcel(){
        Excel.Application excel = null;
        try{
            excel = new Excel.Application();
            return excel;
        }
        catch(Exception ex){
            log(ex.Message);
            return null;
        }
    }
    
    static void ParseFile(string file)
    {
        try
        {
            System.Console.WriteLine("parsing:" + file);            
            Excel.Workbook wb = excel.Workbooks.Open(file);
            Excel.Worksheet ws = wb.Worksheets[1];
            for (int i = 2; i < 27; i++)
            {
                log(ws.Cells[i, 1].Text);
            }
            wb.Close(false);    
        }
        catch (Exception ex)
        {
            log(ex.Message);
        }
        finally{
            Marshal.FinalReleaseComObject(ws);
            Marshal.FinalReleaseComObject(wb);
            ws = null;
            wb = null;
        }
    }
    
    static void CloseExcel(Excel.Application excel){
        try{
            excel.Quit();
        }
        catch(Exception ex){
            log(ex.Message);
        }
        finally{
            Marshal.FinalReleaseComObject(excel);
            excel = null;
        }
    }
    

    Usage:

    Excel.Application excel = OpenExcel();
    if(excel != null){
        // Parse files in a loop
        ParseFile("fileName");
    
        // Close excel after parsing all files
        CloseExcel(excel);
    }
    

提交回复
热议问题