C#为电子表格图表OpenXml添加简单的标题 [英] C# add simple title for spreadsheet chart OpenXml

查看:143
本文介绍了C#为电子表格图表OpenXml添加简单的标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨!!

我可以将图表写入我的 XLSX 文件.但我坚持为每个图表添加一个简单的标题.没有样式,只有简单的纯文本.我的代码是这样的:

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;

但是当我用 excel 打开我的文件时说文件已损坏"或类似的东西.

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

推荐答案

有点晚了但我面临同样的任务,我创建了一个 Excel 表并手动添加了一个带有图表标题的图表,然后打开 xml了解需要哪些标签.过了一会儿,我开始工作了.将所有内容移动到一个小函数中,如下所示:

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.

注意:我使用 Open XML SDK 2.0适用于 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.

这篇关于C#为电子表格图表OpenXml添加简单的标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆