如何修复实例化 Excel.Application 对象时随机出现的 Excel.Application 错误

How to fix Excel.Application error that occurs randomly when instantiating the Excel.Application object

我有一个 c# 程序可以打开 excel 作品sheet,用一些数据填充它,并在关闭 [=25= 之前从作品sheet 中检索一些信息].这在循环内发生多次。该程序执行了一段时间以完成循环,然后在循环期间随机失败并出现以下错误:

System.Runtime.InteropServicdes.COMException (0x80080005): Retrieving the COM class factor for component with CLSID {xxx} failed due to the following error: 80080005 Server execution failed [Exception from HRESULT:0x80080005 (CO_E_SERVER_EXCEC_FAILURE)).

我检查了 Microsoft.Office.Interop.Excel 的参考资料,它是 Microsoft Excel 16.0 对象库版本 1.9.0.0,我安装了 Excel 2016。导致问题的代码类似于以下内容:

for (int i = 0; i < 100; i++)
{
     Excel.Application xlApp;
     Excel.Workbooks xlWorkBooks;
     Excel.Workbook xlWorkBook;
     Excel.Sheets xlWorksheets;
     Excel.Worksheet xlWorkSheet;
     object misValue = System.Reflection.Missing.Value;

     xlApp = new Excel.Application(); //line that causes error

     xlApp.Visible = false;
     xlApp.ScreenUpdating = false;
     xlWorkBooks = xlApp.Workbooks;
     xlWorkBook = xlWorkBooks.Open(IIHSTemplate.Text, 0, false, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
     xlWorksheets = xlWorkBook.Worksheets;
     xlWorkSheet = xlWorksheets["Automatic-Data-Analysis"];
     IIHSDemerit = Convert.ToDouble((xlWorkSheet.Cells[30, 14] as Excel.Range).Value2);

      xlWorkBook.Close(false, misValue, misValue);
      xlApp.Quit();

      releaseObject(xlWorksheets);
      releaseObject(xlWorkSheet);
      releaseObject(xlWorkBooks);
      releaseObject(xlWorkBook);
      releaseObject(xlApp);
}


private void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
                MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
            }
            finally
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }



我的程序将excel数据的结果写入一个文本文件,并执行了几次,没有错误。经过随机次数的迭代(我每次 运行 程序的次数都不同)程序将失败并出现上面列出的错误。关于导致错误的原因以及如何纠正错误的任何想法?

解决方案是将 Excel 应用程序对象的实例化和释放移出循环,因为我只需要在循环内打开和关闭工作簿。感谢@SmrtGrunt 在评论中指出这一点。