如何使用 OpenXML 访问图表标题?

How to access the chart title with OpenXML?

我有一个 excel 文件,里面有一个图表。我希望能够用代码修改图表标题。这是我目前所拥有的:

using (SpreadsheetDocument myWorkbook = SpreadsheetDocument.Open(FilePath, true))
{
   WorkbookPart workbookPart = myWorkbook.WorkbookPart;
   var wsparts = workbookPart.WorksheetParts.ToArray();
   WorksheetPart wsp = GetWorksheetPartByName(myWorkbook, "Sheet1");
   if (wsp.DrawingsPart != null)
   {
         ChartPart chartPart = wsp.DrawingsPart.ChartParts.First();
         //how can I access the chart title here..?
   }
}

获取图表的 chartPart 句柄后,如何访问图表标题?

谢谢

创建图表:

DocumentFormat.OpenXml.Drawing.Charts.Chart chart = chartPart.ChartSpace.AppendChild<DocumentFormat.OpenXml.Drawing.Charts.Chart>(
                new DocumentFormat.OpenXml.Drawing.Charts.Chart());

然后调用方法:

AddChartTitle(chart, "My Chart Title");

写一个访问标题的方法:

private static void AddChartTitle(DocumentFormat.OpenXml.Drawing.Charts.Chart chart, string title)
    {
       var ctitle = chart.AppendChild(new Title());
       var chartText = ctitle.AppendChild(new C.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 });
       ctitle.AppendChild(new Overlay() { Val = new BooleanValue(false) });
        
      }