之前在控制台项目上遇到过微软程序集 Microsoft.Office.Interop.Excel 读取 Excel文件,使用完之后,会有Excel进程驻留无法释放的问题,后来更换了Excel读取组件,就没再研究,最近公司项目需要用到excel宏编程,网上找到了一些解决方案,本地调试OK,发布到服务器上还是无法完全释放Excel进程,导致Excel进程大量驻留的问题,看了很多文章,最终找到了解决方案,这里做下记录:
using System;
using Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
namespace Vlins.Extension
{
/// <summary>
/// Excel Helper
/// </summary>
public class ExcelHelper : IDisposable
{
ApplicationClass _oExcel = null;
Workbooks _oWorkBooks = null;
_Workbook _oBook = null;
public ExcelHelper()
{
_oExcel = new ApplicationClass { Visible = false, DisplayAlerts = false };
_oWorkBooks = _oExcel.Workbooks;
}
/// <summary>
/// 关闭文件释放文件占用
/// </summary>
public void Close()
{
if (_oBook != null)
{
_oBook.Close(false, null, null);
Marshal.ReleaseComObject(_oBook);
}
if (_oExcel != null)
{
Marshal.ReleaseComObject(_oExcel);
}
_oExcel = null;
_oBook = null;
}
public void Dispose()
{
try
{
Close();
if (_oWorkBooks != null)
{
Marshal.ReleaseComObject(_oWorkBooks);
}
if (_oExcel != null)
{
_oExcel.Quit();
Marshal.ReleaseComObject(_oExcel);
}
}
catch (Exception ex)
{
Console.WriteLine("dispose ExcelApp object failed", ex);
}
_oWorkBooks = null;
_oExcel = null;
}
}
}
使用方法:
using (var helper = new ExcelHelper())
{
//处理逻辑
}
另外还需要注意:不要多个进程同时访问同一个文件,这样可能会造成文件占用无法释放,导致excel进程释放失败