Excel Interop Apply Chart Template

狂风中的少年 提交于 2019-12-11 02:26:47

问题


Problem Overview:

I am automating the report generation (excel) for a customer using C# with "native" excel support (microsoft.office.interop.excel) and the EPPlus library.

My customer is not very flexible about charts design so my charts must have the exact same style as theirs.

No problem, i exported their chart templates using Excel 2010

What does not work:

I can't apply any chart template via code

What i have tried:

1 - EPPlus : Have no support for loading templates to charts

2 - InteropExcel : Fails on applying the template raising an exception, here is my code:

        Application excelApp = null;
        Workbook    workbook = null;
        Microsoft.Office.Interop.Excel.Worksheet worksheet = null;

        try
        {
            excelApp  = new Microsoft.Office.Interop.Excel.Application();
            workbook  = excelApp.Workbooks.Open(config.DiretorioRelatorio);
            worksheet = workbook.Sheets[Consts.RECOVERED_SHEET];

            string template = config["templatePath"]; // .crtx file

            ChartObjects charts = worksheet.ChartObjects ();
            ChartObject chart   = ((ChartObject)charts.Item (0));
            chart.Chart.ApplyChartTemplate(template);

        }
        catch (Exception ex)
        {
            Console.WriteLine (ex.Message);
        }
        finally
        {
            workbook.Save ();
            workbook.Close ();
            excelApp.Quit ();

            ReleaseObject (worksheet);
            ReleaseObject (workbook);
            ReleaseObject (excelApp);
        }

This code either throws:

1 - excel interop HRESULT: 0x800A03EC (on casting ChartObjects[0] to ChartObject)

2 - The message filter indicated that the application is busy. (Exception from HRESULT: 0x8001010A (RPC_E_SERVERCALL_RETRYLATER))

TL:DR:

How can i apply a chart template from a file, to an existing chart on my spreadsheet using C# ?

EDIT:

Pastebin code : ExcelInteropProblem


回答1:


Indexes in VBA aren't zero based, so when going from .Net to Excel Interop, you start at 1 even though indexes in C# are, so change this:

ChartObject chart   = ((ChartObject)charts.Item (0));

To this:

ChartObject chart   = ((ChartObject)charts.Item (1));


来源:https://stackoverflow.com/questions/20883776/excel-interop-apply-chart-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!