不废话, 开门见山...
将 调用 Excel 的操作单独写成方法 / 函数, 再写一个方法 / 函数 调用它, 并强制垃圾回收
//Excel 操作
public void DoSomething()
{
Missing missing = Missing.Value;
Excel.Application excel = new Excel.Application();
if (excel == null)
{
MessageBox.Show("打开 Excel 时出错", "");
return;
}
excel.Visible = false;
excel.AlertBeforeOverwriting = false;
excel.DisplayAlerts = false;
Excel.Workbook book = excel.Workbooks.Open(TemplateFile,
missing, missing, missing, missing, missing, missing, missing,
missing, missing, missing, missing, missing, missing, missing);
if (book == null)
{
MessageBox.Show("打开 Excel 时出错", "");
return;
}
Excel.Worksheet sheet = book.Sheets[1] as Excel.Worksheet;
if (sheet == null)
{
MessageBox.Show("打开 Excel 时出错", "");
return;
}
try
{
//do something
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "意外");
}
finally
{
sheet.SaveAs("c:\1.xls", missing, missing, missing, missing, missing, missing, missing, missing, missing);
book.Save();
excel.Workbooks.Close();
excel.Quit();
sheet = null;
book = null;
excel = null;
}
}
//调用 DoSomething()
public void ExportData()
{
try
{
DoSomething();
}
catch (Exception)
{
//Error
}
finally
{
//垃圾回收
GC.Collect();
}
}