質問

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

役に立ちましたか?

解決

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));
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top