C# add simple title for spreadsheet chart OpenXml

筅森魡賤 提交于 2021-01-28 11:33:58

问题


Hi!!

i'm able to write charts to my XLSX file. But i'm stuck adding a simple title for every chart. No styles just simple plain text. My code is like this:

 String Dtitulo = "Hello chart";
 DocumentFormat.OpenXml.Drawing.Charts.Title chartTitle = new DocumentFormat.OpenXml.Drawing.Charts.Title();                
 chartTitle.ChartText = new ChartText();                    
 chartTitle.ChartText.RichText = new RichText();
 DocumentFormat.OpenXml.Drawing.Paragraph parrafoTitulo = new DocumentFormat.OpenXml.Drawing.Paragraph();
 DocumentFormat.OpenXml.Drawing.Run run = parrafoTitulo.AppendChild(new DocumentFormat.OpenXml.Drawing.Run());
 run.AppendChild(new DocumentFormat.OpenXml.Drawing.Text(Dtitulo));

chartTitle.ChartText.RichText.AppendChild<DocumentFormat.OpenXml.Drawing.Paragraph>(parrafoTitulo);
chart.Title = chartTitle;

But when i open my file with excel says "file is corrupt" or something like that.


回答1:


A bit late but I was faced with the same task, and I created an excel sheet and added manually a chart with a chart title, then opened the xml to understand what tags were needed. And after a while I got it working. moved everything in a small function as below:

So you can provide your chart object and the title you want to the below function and it will add the chart title.

Note:Im using Open XML SDK 2.0 for Microsoft Office

private void AddChartTitle(DocumentFormat.OpenXml.Drawing.Charts.Chart chart,string title)
    {
        var ctitle = chart.AppendChild(new Title());
        var chartText = ctitle.AppendChild(new ChartText());
        var richText = chartText.AppendChild(new RichText());

        var bodyPr = richText.AppendChild(new BodyProperties());
        var lstStyle = richText.AppendChild(new ListStyle());
        var paragraph = richText.AppendChild(new Paragraph());

        var apPr = paragraph.AppendChild(new ParagraphProperties());
        apPr.AppendChild(new DefaultRunProperties());

        var run = paragraph.AppendChild(new DocumentFormat.OpenXml.Drawing.Run());
        run.AppendChild(new DocumentFormat.OpenXml.Drawing.RunProperties() { Language = "en-CA" });
        run.AppendChild(new DocumentFormat.OpenXml.Drawing.Text() { Text = title });
    }

And if you want a full example, you can review the official one here, and inject the above function in the right place (after the creation of the chart object) and it will add the chart title.



来源:https://stackoverflow.com/questions/42521752/c-sharp-add-simple-title-for-spreadsheet-chart-openxml

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