簡體   English   中英

如何在.docx文件中找到純文本內容控件,並使用OpenXML SDK替換其中的文本?

[英]How do I find plain-text content controls within a .docx file and replace the text within using the OpenXML SDK?

我正在開發一個需要將數據輸出到Word文檔的程序,在其中放置了帶有標簽的純文本內容控件。 基本上,我正在編寫以下方法(使用C#)...

public static void SetContentControlText(WordprocessingDocument document, string contentControlTag, string text)
{
    // TODO: Implement this method...
}

該方法應該能夠用指定的標簽填充所有純文本內容控件,而不管它們在文檔結構中的位置如何(即,它應該能夠在文檔主體中找到內容控件以及內部表格等)。

提前致謝!

經過深入研究后,我發現/采用了以下解決方案...

public static int SetContentControlText(
    this WordprocessingDocument document,
    Dictionary<string, string> values)
{
    if (document == null) throw new ArgumentNullException("document");
    if (values == null) throw new ArgumentNullException("values");

    int count = 0;

    foreach (SdtElement sdtElement in document.MainDocumentPart.Document.Descendants<SdtElement>())
    {
        string tag = sdtElement.SdtProperties.Descendants<Tag>().First().Val;
        if ((tag != null) && values.ContainsKey(tag))
        {
            sdtElement.Descendants<Text>().First().Text = values[tag] ?? string.Empty;
            sdtElement.Descendants<Text>().Skip(1).ToList().ForEach(t => t.Remove());

            count++;
        }
    }

    return count;
}

該方法接收文檔和標記/值對的字典,並返回設置的內容控件的數量!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM