创建 powerpoint 图表时额外 Excel 应用程序打开

Extra Excel Application Opening while creating powerpoint charts

我正在用 PowerPoint 创建图表。下面的代码打开两个 excel 应用程序。一个在不可见的背景中打开。第二个在方法结束后打开。我需要确保第二个 excel 要么永远不会打开,要么我可以在打开后关闭它。

我尝试了以下方法,但 none 有效。

I have tried forcing GC, Manual ReleaseComObject, Killing Excel process

I have tried separating excel COM objects and forcing GC

private void BtnInsert_Click(object sender, EventArgs e)
{
    var Addin = Globals.ThisAddIn;
    Microsoft.Office.Interop.PowerPoint.Application activeApplication = Addin.Application;
    DocumentWindow activeWindows = activeApplication.ActiveWindow;
    Microsoft.Office.Interop.PowerPoint.View activeView = activeWindows.View;
    Slide activeSlide = activeView.Slide;

    Microsoft.Office.Interop.PowerPoint.Shapes slideShape = activeSlide.Shapes;
    Microsoft.Office.Interop.PowerPoint.Shape shape = slideShape.AddChart2(-1, XlChartType.xl3DBarClustered, -1, -1, -1, -1, true);
    Microsoft.Office.Interop.PowerPoint.Chart chart = shape.Chart;

    //Access the chart data
    Microsoft.Office.Interop.PowerPoint.ChartData chartData = chart.ChartData;
    chartData.Activate();

    //Create instance to Excel workbook to work with chart data
    Workbook workbook = chartData.Workbook;
    Microsoft.Office.Interop.Excel.Application workbookApplication = workbook.Application;
    workbookApplication.Visible = false;
    workbookApplication.WindowState = XlWindowState.xlMinimized;

    //Accessing the data worksheet for chart
    Worksheet worksheet = workbook.Worksheets[1];

    // I am adding data here
    // This is not required to reproduce this

    chartData.BreakLink();
    workbook.Close(true);
}

另请注意,更新数据时不会发生此问题。

删除 chartData.Activate()chartData.BreakLink() 解决了这个问题。 尽管联机文档说在访问工作簿之前需要 chartdata.activate。 否则,我们将得到一个空引用。

我认为文档不正确或不适用于 vsto。