保存文件后,用C#关闭Excel

时间:2020-04-27 12:51:04

标签: c# excel

我正在使用C#将一些信息写入Excel文件:

using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using Microsoft.Office.Interop.Excel;
using Excel = Microsoft.Office.Interop.Excel;
using System.Globalization;

public void OpenExcel(string folder, string filename)
{
    this.folder = folder;
    this.filename = filename;
    path = folder + @"\" + filename;

    if (File.Exists(path) != true) //if the output file does not exists, create it
    {
        var app = new Microsoft.Office.Interop.Excel.Application();
        var temp = app.Workbooks.Add();
        temp.SaveAs(path);
        temp.Close();
    }

    wb = excel.Workbooks.Open(path);
}

完成并保存文件后,我想关闭它:

public void Close()
{
    wb.Close(false);

    excel.Quit();
    excel.Application.Quit();

    System.Runtime.InteropServices.Marshal.ReleaseComObject(workSheet);
    System.Runtime.InteropServices.Marshal.ReleaseComObject(wb);
    System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);

    workSheet = null;
    wb = null;
    excel = null;

    GC.Collect();
    GC.WaitForPendingFinalizers();
    GC.Collect();
}

以上两个空位都是名为ExcelFile的类对象的一部分。但是,当我使用上面的代码并退出我制作的程序时,Excel仍然像下面的问题一样留作后台进程:C# closing Excel after using

我已经看到关于这个主题的stackoverflow上有一些线程,但是似乎没有解决方案对我有用。我想避免尽可能地杀死所有Excel进程,因为这是一个程序,将使用thread pool进行计算,这将花费数小时。

0 个答案:

没有答案
相关问题