在Microsoft Excel从应用程序外部打开且无法closures的情况下,C#应用程序中使用的Excel文件变得可见

我正在使用Interop Excel,我的代码工作正常

class GeneralData { public static string excelPath = System.Windows.Forms.Application.StartupPath + @"\SteamProp"; public static ExcelApp._Application oExcel; static ExcelApp.Workbooks oBooks; public static ExcelApp._Workbook oBook; static object oMissing = System.Reflection.Missing.Value; // Function will be used in Main Form Load Method public static void OpenExcelConnection() { oExcel = new ExcelApp.Application(); oExcel.Visible = false; oBooks = oExcel.Workbooks; oBook = oBooks.Open(excelPath, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing); } public static void ReleaseExcel() { try { oBook.Close(true, excelPath, oMissing); oExcel.Quit(); System.Runtime.InteropServices.Marshal.FinalReleaseComObject(oBook); System.Runtime.InteropServices.Marshal.FinalReleaseComObject(oBooks); System.Runtime.InteropServices.Marshal.FinalReleaseComObject(oExcel); oBook = null; oBooks = null; oExcel = null; GC.Collect(); GC.WaitForPendingFinalizers(); } catch { } } 

我使(OExcel)静态使用它从不同的forms。 我打开(OExcel)并使用它,最后通过调用ReleaseExcel()方法closures它。 代码工作正常,但如果从应用程序外部打开了任何不同的excel文件,那么在C#应用程序中使用的文件对用户来说即使是这样:

 oExcel.Visible = false; 

当ReleaseExcel()方法调用这个文件没有closures时,如果我closures了C#应用程序,并再次打开它,则会引发下一个exception:

Microsoft Jet数据库引擎无法打开该文件“它已经被另一个用户独占打开,或者您需要权限来查看其数据。

那么你能帮助我吗?

完成对象的处理后,请使用

 GC.Collect(); 

这是我如何处理我的Excel对象

  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(); } }