发布创建的excel实例

时间:2013-03-12 06:35:37

标签: c# excel

我试图将一个工作表的副本复制到另一个工作表,下面是我的代码。我试图释放创建的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);                
}

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

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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

这段代码应该有所帮助:

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

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

还按此顺序销毁对象: 范围等 工作表 工作簿 APP

像这样:

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来捕获本节中的错误。

相关问题