代码之家  ›  专栏  ›  技术社区  ›  Timmo

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

  •  0
  • Timmo  · 技术社区  · 7 年前

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

    当我尝试导入多个图表时,我得到一个 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。复制();
    

    为此:

    objChart.CopyPicture();
    

    1 回复  |  直到 7 年前
        1
  •  0
  •   Timmo    7 年前

    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);