簡體   English   中英

在Excel加載項中正確處理Excel COM對象

[英]properly disposing of Excel COM object in Excel Add in

好的,我相信這個問題一定已經被問過一百萬遍了,因此我很抱歉重復一次,但是我無法弄清楚為什么在運行此應用程序后仍在任務管理器中獲得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的簡單復制/粘貼,但是在繼續進行此應用程序的其余部分之前,我想確保在此處正確進行復制/粘貼。

嗯,嘗試只使用:

Marshal.ReleaseComObject(YourComApp);

如果仍然不行,請在將其上運行元帥后嘗試使COM對象無效。 我知道在Powershell中我也必須轉儲變量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM