1

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

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

4

2 回答 2

0

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

xlApp.Quit()
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp)
xlApp = Nothing
xlBook = Nothing
xlSheet = Nothing
于 2013-03-12T06:41:59.953 回答
0

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

此代码应该有帮助:

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

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

还按此顺序销毁您的对象:范围等 Worksheets Workbook 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 捕获本节中的错误。

于 2013-03-12T06:47:07.240 回答