实际上,这两个代码示例都会让 Excel 进程在后台运行。例如,您需要调用Application.Quit()
应用程序对象。以下作品:
private static void DoExcel()
{
var application = new Application();
var workbook = application.Workbooks.Add();
var worksheet = workbook.Worksheets.Add();
// Name that this will be saved as
string name = workbook.FullName + ".xlsx";
string fullPath = Path.Combine(Directory.GetCurrentDirectory(), name);
// If a file of the same name exists, delete it so that we won't be prompted if
// we want to overwrite it when we save
if (File.Exists(fullPath))
File.Delete(fullPath);
// Save the workbook - otherwise we may be prompted as to whether we want to save when we go to quit
workbook.Save();
// Quit the application
application.Quit();
// Release the references
Marshal.ReleaseComObject(worksheet);
Marshal.ReleaseComObject(workbook);
Marshal.ReleaseComObject(application);
// Release the .NET reference and run the garbage collector now to make sure the application is closed immediately
worksheet = null;
GC.Collect();
GC.WaitForPendingFinalizers();
}
还有一些需要记住的好东西:我没有在这里使用它,但是有一个Marshal.FinalReleaseComObject 方法在这些情况下非常有用。此外,我再次在我的代码示例中没有使用它,但是该Marshal.ReleaseComObject
方法返回当前计数,因此如果您想确保计数达到零,您总是可以在循环中执行释放:
while (Marshal.ReleaseComObject(comObject) > 0) { }
您也可以将其用于调试目的 - 例如
int count = Marshal.ReleaseComObject(comObject);
Trace.TraceInformation("Current COM object reference count: " + count.ToString());