当前位置: 代码迷 >> 综合 >> EXCEL application.quit 不关闭进程问题解决
  详细解决方案

EXCEL application.quit 不关闭进程问题解决

热度:12   发布时间:2024-02-22 00:25:59.0

EXCEL application.quit 不关闭进程问题解决

直接上源码

        public bool Format(string filePath, string outputFile){
    var excelApplication = new Microsoft.Office.Interop.Excel.Application();Workbook workbook = null;XlFixedFormatType targetType = XlFixedFormatType.xlTypePDF; //PDF格式try{
    workbook = excelApplication.Workbooks.Open(filePath);if (!File.Exists(outputFile)) //存在PDF,不需要继续转换{
    workbook.ExportAsFixedFormat(targetType, outputFile);}}catch (Exception e){
    Console.WriteLine(e);return false;}finally{
    NAR(targetType);workbook?.Close();NAR(workbook);excelApplication.Quit();NAR(excelApplication);GC.Collect();}return true;/// <summary>/// 释放资源/// </summary>/// <param name="o"></param>private void NAR(object o){
    try{
    Console.WriteLine(o);Console.WriteLine(System.Runtime.InteropServices.Marshal.FinalReleaseComObject(o));}catch {
     }finally{
    o = null;}}

这个版本看起来没问题,但是我实际测试,无论怎么搞,excel进程依然存在。
最终解决方案

 var workbooks = excelApplication.Workbooks;workbook = workbooks.Open(filePath);NAR(targetType);workbook?.Close();NAR(workbook);workbooks?.Close();NAR(workbooks);excelApplication.Quit();NAR(excelApplication);GC.Collect();
  相关解决方案