您的位置:首页 > 编程语言

常见.NET功能代码汇总 (3)

2017-06-24 15:45 218 查看

33,彻底关闭Excel进程

.NET中使用Excel属于使用非托管资源,使用完成后一般都要用GC回收资源,但是,调用GC的位置不正确,Excel进程可能无法彻底关闭,如下面的代码:

static void OpenExcelTest(int j)
{
//Application excel = null;
excel = new Application();
excel.Visible = true;
excel.Workbooks.Open("d:\\A1000.xla");
Workbook wb = excel.Application.Workbooks.Open("d:\\Book1.xlsx");
Worksheet sh = wb.Worksheets.Item["Sheet1"];
object[,] ssss = sh.Range[sh.Cells[1.1], sh.Cells[3, 1]].Value2;
Console.WriteLine("opened excel no. {0}", j);
Console.ReadLine();

try
{
//尝试程序关闭Excel进程
wb.Close(false);
sh = null;
wb = null;
excel.Quit();
}
catch (Exception ex)
{
Console.WriteLine("用户已经手工结束了Excel进程,内部错误消息:{0}",ex.Message );
}

int generation = System.GC.GetGeneration(excel);

//No.1
//System.Runtime.InteropServices.Marshal.ReleaseComObject(wb);
//System.Runtime.InteropServices.Marshal.ReleaseComObject(sh);
//System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);

excel = null;
//No.2
//GC.Collect(generation);

Console.WriteLine("close excel no. {0}", j);
Console.ReadLine();
}


在上面的代码中,如果取消 No.1,No.2位置处的注释,方法结束后,Excel进程是无法结束的,解决办法,只需要把
GC.Collect();
这行代码写到方法之外即可。

Application excel = null;
这个Excel应用程序对象定义在方法内或者外都是可以的,哪怕定义一个静态变量,结果都没有影响。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: