2016-11-16 4 views
0

私はタグ付けされたプレーンテキストのコンテンツコントロールを配置したWord文書にデータを出力する必要があるプログラムに取り組んでいます。基本的に、私はこの方法に関係なく、構造内での位置の、指定したタグを持つすべてのプレーンテキストコンテンツコントロールを記入することができるはずOpenXML SDKを使用して、.docxファイル内のプレーンテキストコンテンツコントロールを検索し、そのテキストを置き換えるにはどうすればよいですか?

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

...(C#を使用して)次のような方法を書いた後です(つまり、文書の本体と表の中のコンテンツコントロールを見つけることができるはずです。

ありがとうございます!

答えて

0

一部が周り掘り行った後、私は/には、以下のソリューションを適応したが...

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; 
} 

方法は、文書とタグ/値のペアの辞書に取り、そのコンテンツコントロールの数を返します。セットされました!

関連する問題