Excel是一个很特殊的东西,所有对它的操作都是独占的,因此就有必要在资源释放上严格进行。下面就附上一段小代码,为了能够更快更容易说明问题,代码经过了删减,只保存了结构的完整性,代码如 下:
需要引用的命名空间
using Execl = Microsoft.Office.Interop.Excel;

try
{
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook workbook = excel.Workbooks.Open(lujing2, System.Type.Missing, false , System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing);
excel.Visible = true ;
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets.get_Item( 1 );
// 开始执行Excel操作
if (excel.ActiveWorkbook.Saved == false )
{
excel.ActiveWorkbook.Save();
}
excel.Quit();
excel = null ;
Application.Exit();
GC.Collect(System.GC.GetGeneration(worksheet));
GC.Collect(System.GC.GetGeneration(workbook));
GC.Collect(System.GC.GetGeneration(excel));
}
catch
{
}
finally
{
GC.Collect();
}
同时,这里有一个比较有争议的问题,我特此声明下:微软强烈建议不要通过GC.Collect方法来强制执行垃圾手机,因为那会妨碍GC本身的工作方式。只有在明确知道有大量对象停止引用时,才考虑使用GC.Collect方法来调用收集器。
微软针对excel提供的com还是非常不错的,还请朋友们不要错怪于它。