在Excel中正确处理Excel COM对象

时间:2016-01-25 03:37:07

标签: c# excel com

好的,我相信这个问题肯定已被问过一百万次了,所以对复制道歉,但我无法弄清楚为什么我在运行这个应用程序后仍然在我的任务管理器中获得一个COM对象。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Tools.Ribbon;
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Core;
using System.Reflection;
using System.Runtime.InteropServices;

namespace DataDumpTest
{
public partial class DataDumpRibbon
{
    private Excel.Application _xlApp = null;
    private Excel.Workbook _wb = null;
    private Excel.Worksheet _ws = null;

    private void DataDumpRibbon_Load(object sender, RibbonUIEventArgs e)
    {

    }

    private void LoadOpenFileDialog()
    {
        this.openFileDialog1.Filter = "Excel File (*.XLSX) | *.XLSX";
        this.openFileDialog1.Title = "Ariel's Special Definition";
        this.openFileDialog1.Multiselect = false;
    }

    private void btnDataDump_Click(object sender, RibbonControlEventArgs e)
    {
        LoadOpenFileDialog();

        if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            _xlApp = new Excel.Application();
            _xlApp.Visible = false;
            _xlApp.DisplayAlerts = false;
            _xlApp.ScreenUpdating = false;
            _wb = _xlApp.Workbooks.Open(openFileDialog1.FileName);
            _ws = _wb.Worksheets["Sheet1"];

            _ws.UsedRange.Copy(Type.Missing);
            // get range to paste into
            Excel.Worksheet activeWs = Globals.ThisAddIn.Application.ActiveSheet;
            if (activeWs != null)
            {
                Excel.Range rng = activeWs.Cells[1, 1];
                rng.Select();
                Globals.ThisAddIn.Application.ActiveSheet.Paste(Type.Missing, Type.Missing);
            }

            // clean up
            GC.Collect();
            GC.WaitForPendingFinalizers();
            Marshal.FinalReleaseComObject(_ws);
            _wb.Close(Type.Missing, Type.Missing, Type.Missing);
            Marshal.FinalReleaseComObject(_wb);
            _xlApp.Quit();
            Marshal.FinalReleaseComObject(_xlApp);
        }
    }
}
}

所以我有兴趣处理的COM对象是我通过OpenfileDialog1打开的_xlApp,_wb和_ws。当我调试这个时,我可以在我的任务管理器中看到,当我按下按钮时,另一个Excel实例显示并且在我停止调试器之前不会消失。当我释放它们时,它不应该消失吗?我在这里错过了什么吗?

聚苯乙烯。这只是从一个excel到另一个excel的简单复制/粘贴,但我想确保在我继续使用此应用程序的其余部分之前将其解决。

1 个答案:

答案 0 :(得分:1)

嗯,试试吧:

Marshal.ReleaseComObject(YourComApp);

如果仍然没有,请在运行Marshal之后尝试将COM对象清空。我知道在powershell中我也必须转储变量。