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

本文关键字:查找 图形部 控件 文本 OpenXML SDK 使用 | 更新日期: 2023-09-27 18:15:56

各位开发人员好,

作为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
                }
            }
        }

非常感谢你的帮助

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

我自己找到解决办法了。我现在不使用父容器。相反,我给图表空间一个"Alt Title"。现在我的代码寻找具有给定标题的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();
                        }
                    }
                }
            }
        }
    }
}