Excel / Powerpoint Office Interop - 将图表从Excel工作表复制到Powerpoint幻灯片

时间:2017-08-14 11:48:06

标签: c# excel interop office-interop excel-interop

我有一个包含多个图表的Excel工作簿。我创建了一个for循环来获取每张表中的图表。这没有错误。

我遇到的问题是我无法导入多个图表,只能导入一个图表而导入的图片不是图表。

当我尝试导入多个图表时,我会在此行中获得COMException

objChart.Copy();

完整错误:

An exception of type 'System.Runtime.InteropServices.COMException' occurred in mscorlib.dll but was not handled in user code

Additional information: Exception from HRESULT: 0x800A03EC

这是我的完整方法:

public int ImportExcelChartsFromWorkbookToSlides(int startingSlideIndex, string workbookPath, string[] slideTitles)
{
    int slideIndex = startingSlideIndex;
    int titleIndex = 0;
    EXCL.Application objExclApp = new EXCL.Application();
    EXCL.Workbook objWorkbook = objExclApp.Workbooks.Open(workbookPath, Editable: false);
    foreach (EXCL.Worksheet objSheet in objWorkbook.Worksheets)
    {
        foreach (EXCL.ChartObject objChart in objSheet.ChartObjects())
        {
            AddTitleOnlySlide(slideIndex);
            SetTitleOnlySlideTitle(slideTitles[titleIndex]);

            // Copy Chart from Sheet to Slide
            objChart.Copy();

            PPT.ShapeRange objShapeRange = objSlide.Shapes.Paste();

            // TODO PARAMETER
            objShapeRange.Left = 10;
            objShapeRange.Top = 100;

            slideIndex++;
            titleIndex++;
        }
    }
    return slideIndex;
}

是否有人发现此代码存在任何问题?

更新

如果我更改此行:

objChart.Copy();

到此:

objChart.CopyPicture();

我没有问题。可能导致这种情况的原因是什么?

1 个答案:

答案 0 :(得分:0)

我设法使用objChart.CopyPicture();解决了这个问题,但对于某些用户来说这是causing crashes,所以我最终这样做了:

string chartPath = $@"{workbookPath.Substring(0, workbookPath.LastIndexOf("\\") + 1)}{DateTime.Now.Ticks}.png";
objChart.Chart.Export(chartPath, "PNG", false);
objSlide.Shapes.AddPicture2(chartPath, MsoTriState.msoFalse, MsoTriState.msoTrue, chartPosLeft, chartPosTop, compress: MsoPictureCompress.msoPictureCompressFalse);