これを行う最も簡単な方法は、文字列の置換です。テンプレートを制御できるので、マージフィールドに一意の文字列を配置します。差し込みフィールドがフォーマットされているかどうかにかかわらず、置き換える必要のあるテキストはText
要素になります。
Body
のテキストのすべての子孫をWordprocessingDocument
で検索し、文字列置換を行います。
ここには、[FAX結合ドキュメント]テンプレートのスナップがあります。私は«XXXXBusiness PhoneXXXX»をするビジネス電話マージフィールドを変更し、それを異なってフォーマットされています
using System.Linq;
using DocumentFormat.OpenXml.Wordprocessing;
namespace OxmlApp
{
static class WordprocessingExtensions
{
public static void ReplaceTextInTextDescendants(this Body body, string oldText, string newText)
{
foreach (var textItem in body.Descendants<Text>().Where(textItem => textItem.Text.Contains(oldText)))
{
textItem.Text = textItem.Text.Replace(oldText, newText);
}
}
}
}
:

私はそうのように置き換える行うにBody
クラスの拡張メソッドを書きましたこれを実行すると、文書を開いた後にコードが1行で表示されます。
using (var doc = WordprocessingDocument.Open(openFileDialog.FileName, true))
{
doc.MainDocumentPart.Document.Body.ReplaceTextInTextDescendants("«XXXXBusiness PhoneXXXX»","212-867-5309");
}
結果は次のようになります。ここEEN:

をやりました!