【问题标题】:Release excel instance created发布创建的excel实例
【发布时间】:2013-03-12 14:47:07
【问题描述】:

我正在尝试将一个工作表的副本复制到另一个工作表,下面是我的代码..我尝试释放由 excel 创建的实例,但我仍然在 TaskManager 中看到它的一个实例。

C#代码:

try
{
  wBook = xCel.Workbooks.Open(filePath);
  xCel.Visible = false;
  this.xCel.DisplayAlerts = false;                
  wBook = (Excel.Worksheet)wBook.Worksheets.get_Item(1);
  wBook.Copy(Type.Missing, Type.Missing);                
  wBook = (Excel.Worksheet)wBook.Sheets[1];                
  wBook.SaveAs(strFileCopyPath);                 
}
finally
{
  if (wBook != null)
  {   wBook.Close();                    
      Thread.Sleep(500);
  }                
  Marshal.ReleaseComObject(wBook);               
  Marshal.ReleaseComObject(wBook);                
}

请有人告诉我在这里做错了什么? 谢谢

【问题讨论】:

  • 请参阅here 了解如何以及何时释放对象,here 了解限制使用“两个点”。当您调用 wBook.Worksheets.get_Item(1); 时,会创建一个中间 Worksheets 对象,但由于您没有对它的引用,因此无法释放它。

标签: c# excel


【解决方案1】:

你没有做任何理智的错误 - 但关闭 exel 的概念非常轻率。 那是因为: 1:Excel 有时会创建中间对象,这些对象对您来说是不可见的,尤其是当您执行以下操作时:DIm bla = excel.worksheet.range("A1").value。然后是excel的中间对象。 2:必须以非常特定的顺序关闭 excel 对象。

这段代码应该有帮助:

GC.Collect()
GC.WaitForPendingFinalizers()
GC.Collect()
GC.WaitForPendingFinalizers()

这必须是双倍的,因为 pass 1 只标记中间对象,但不会破坏它们。这是垃圾收集。

还按以下顺序销毁您的对象: 范围等 工作表 工作簿 应用程序

像这样:

System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlSheet)
xlsheet = nothing
xlBook .Close()
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlBook )
xlbook = nothing
xlapp.quit
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlapp)
xlapp = nothing

如果对象什么都不是,请使用 try catch 来捕获本节中的错误。

【讨论】:

    【解决方案2】:

    您忘记调用Excel.Application 对象的Quit() 方法。通常我使用以下代码关闭 Excel(VB.Net 代码 sn-p):

    xlApp.Quit()
    System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp)
    xlApp = Nothing
    xlBook = Nothing
    xlSheet = Nothing
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-12
      • 2021-08-05
      • 1970-01-01
      • 2011-04-16
      • 2016-08-17
      • 1970-01-01
      相关资源
      最近更新 更多