【发布时间】:2016-03-18 03:07:28
【问题描述】:
我正在使用 C# 中的 Visual Studio 2015 Community,以及独立的 Office 2013。
以下代码用于打开和关闭 Excel。然后我添加了代码来打开特定的工作表,如下面的示例 2 所示。而且,这行得通,Excel 正确关闭。
然后我移动了一些东西,但忘记使用 ReleaseComObject 作为工作表并且 Excel 保持打开状态,所以我在任务管理器中手动将其关闭。
现在,以下示例均无效。在我不小心忘记释放 COM 对象后,Excel 永远不会关闭,除非我重新启动机器。
示例 1
private bool loadExcel()
{
// Open Excel
Excel.Application myApp = new Excel.Application();
// Hide Excel
myApp.Visible = false;
GSIWorkbook = myApp.Workbooks.Open( "D:\\Test.xlsx" );
// Cleanup
GSIWorkbook.Close( false );
// Manual disposal because of COM
while ( System.Runtime.InteropServices.Marshal.ReleaseComObject( GSIWorkbook ) != 0 )
{ }
myApp.Application.Quit();
myApp.Quit();
while ( System.Runtime.InteropServices.Marshal.ReleaseComObject( myApp ) != 0 )
{ }
myApp = null;
GSIWorkbook = null;
GC.Collect();
GC.WaitForPendingFinalizers();
return true;
} // End loadExcel
示例 2
private bool loadExcel()
{
// Open Excel
Excel.Application myApp = new Excel.Application();
// Hide Excel
myApp.Visible = false;
GSIWorkbook = myApp.Workbooks.Open( "D:\\Test.xlsx" );
for ( int counter = 1; counter < 100; counter++ )
{
try
{
GSIWorksheet = GSIWorkbook.Sheets[counter];
if ( GSIWorksheet.Name == _gsi2Sheet )
break;
}
catch
{
continue;
}
}
while ( System.Runtime.InteropServices.Marshal.ReleaseComObject( GSIWorksheet ) != 0 )
{ }
// Cleanup
GSIWorkbook.Close( false );
// Manual disposal because of COM
while ( System.Runtime.InteropServices.Marshal.ReleaseComObject( GSIWorkbook ) != 0 )
{ }
myApp.Application.Quit();
myApp.Quit();
while ( System.Runtime.InteropServices.Marshal.ReleaseComObject( myApp ) != 0 )
{ }
myApp = null;
GSIWorkbook = null;
GC.Collect();
GC.WaitForPendingFinalizers();
return true;
} // End loadExcel
【问题讨论】:
-
你是说VS社区吗?视觉工作室?
-
"Excel 永远不会关闭,除非我重新启动我的机器。" ...或者,只需打开任务管理器并终止所有剩余的“excel.exe”进程。
-
正如我上面所说,我使用的是 C#,而不是 VB,而且我不会在任何地方使用“.Add”。在任务管理器中杀死不是一个干净的解决方案,使用 proc.Kill() 将杀死所有 Excel 实例。我知道我可以发现进程 ID (PID),然后只杀死该进程。但这也感觉像一个kluge。完成后必须有一种干净的方法来关闭 Excel。