使用 OpenXML SDK 在富文本控件中查找图形部分

Joh*_*han 2 c# openxml-sdk

各位开发者好,

作为 OpenXML SDK 的新手,我无法弄清楚如何检索我放入富文本控件(具有特定标记名称)中的图形部分。

目前,我使用 mainDocumentPart.ChartParts 集合检索图形部分。但是 ChartPart 对象似乎不知道它在文档中的位置:chartPart.GetParentParts() 只包含 mainDocumentPart。

我的文档中有多个图形,那么如何区分它们? 我已经把我的图表放在富文本控件中,所以我想我可以这样访问它们,但我不知道如何做到这一点。检索富文本控件有效,但如何在其中查找图形?

        foreach (SdtProperties sdtProp in mainDocumentPart.Document.Body.Descendants<SdtProperties>())
        {
            Tag tag = sdtProp.GetFirstChild<Tag>();

            if (tag != null && tag.Val != null)
            {
                if (tag.Val == "containerX")
                {
                    SdtProperties sdtPropTestResults = sdtProp;

                    // How to retrieve the graph part??
                    // sdtPropTestResults.Descendants<ChartPart> does not seem to work
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

非常感谢你的帮助。

Joh*_*han 5

自己找到了解决办法。我现在不使用父容器。相反,我给图表空间一个“替代标题”。现在我的代码查找具有给定标题的 docProperties 的绘图。

这里是:

// Find our graphs by looping all drawings in the document and comparing their "alt title" property
foreach (Drawing drawing in mainDocumentPart.Document.Body.Descendants<Drawing>())
{
    DocProperties docProperties = drawing.Descendants<DocumentFormat.OpenXml.Drawing.Wordprocessing.DocProperties>().FirstOrDefault();

    if (docProperties != null && docProperties.Title != null)
    {
        if (docProperties.Title.Value == AltTitleChartBlack || docProperties.Title.Value == AltTitleChartRed)
        {
            LineChartData lineChartData = null;
            switch (docProperties.Title.Value)
            {
                case AltTitleChartBlack:
                    lineChartData = this.chartDataBlack;
                    break;
                case AltTitleChartRed:
                    lineChartData = this.chartDataRed;
                    break;
            }

            ChartReference chartRef = drawing.Descendants<ChartReference>().FirstOrDefault();
            if (chartRef != null && chartRef.Id != null)
            {
                ChartPart chartPart = (ChartPart)mainDocumentPart.GetPartById(chartRef.Id);
                if (chartPart != null)
                {
                    Chart chart = chartPart.ChartSpace.Elements<Chart>().FirstOrDefault();
                    if (chart != null)
                    {

                        LineChart lineChart = chart.Descendants<LineChart>().FirstOrDefault();

                        if (lineChart != null)
                        {
                            LineChartEx chartEx = new LineChartEx(chartPart, lineChartData);
                            chartEx.Refresh();
                            chartPart.ChartSpace.Save();
                        }
                    }
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)