主要原因是:程序并没有完全释放掉使用的资源,虽然程序正常关闭,程序本身也可以自动释放原来使用的资源,但Excel进程并不能判断到,只要Excel使用的资源有没有释放的,Excel进程就不会关闭。
解决办法:使用完Excel.Application对象后,关闭所有使用资源。如:app._Workbools / Sheets / _Workbook 等,最后 app.Quit()。
以下是我写的一个分析指定 Excel 文件子表名列表的方法,供参考:
///
/// 获得指定 xls 文件中 Sheet 子表名的列表
///
///
///
public static string[] GetSheetList(string xlsFile)
{
if (!File.Exists(xlsFile))
{
return null;
}
// 初始化 Excel 组件变量
object opt = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Excel.Application app = null;
_Workbook book = null;
Sheets sheets = null;
_Worksheet[] wsArray = null;
app = new Microsoft.Office.Interop.Excel.Application();
book = app.Workbooks.Open(xlsFile, opt, true, opt, opt, opt, true, opt, opt, opt, false, opt, opt, opt, opt); // 只读,不可编辑;
sheets = book.Worksheets;
// 列举出所有表
wsArray = new _Worksheet[sheets.Count];
string[] sheetNames = new string[sheets.Count];
for (int i = 0; i < sheets.Count; i++)
{
wsArray[i] = (_Worksheet)sheets.get_Item(i + 1); // 从 1 开始索引
sheetNames[i] = wsArray[i].Name;
}
app.Workbooks.Close(); // 关闭所有工作 Book
app.Quit();
// 强制回收 Excel 进程
int geneID = System.GC.GetGeneration(app);
wsArray = null;
sheets = null;
book = null;
app = null;
System.GC.Collect(geneID);
return sheetNames;
}
Excel对象使用后进程不能退出的完美解决办法
最新推荐文章于 2022-07-19 17:37:36 发布