LoginSignup
2
2

More than 1 year has passed since last update.

C#からWordテンプレートに文字を挿入する方法

Last updated at Posted at 2020-03-30

Word側の設定

  • 挿入 > クイックパーツ > フィールド
  • MergeFieldを選択
  • フィールド名に適当な名前をつける(c#から参照する名前。例:CustomerName)
using Microsoft.Office.Interop.Word;

// テンプレートのファイルパス
private string template = @"C:\tmp\template.docx";

public void InsertWord(string field, string word)
{
    object missing = Type.Missing;
    var app = new Application();
    var doc = app.Documents.Open(template, ref missing, true);

    foreach (Field myMergeField in doc.Fields)
    {
        Range rngFieldCode = myMergeField.Code;
        String fieldText = rngFieldCode.Text;
        if (fieldText.StartsWith(" MERGEFIELD"))
        {
            Int32 endMerge = fieldText.IndexOf("\\");
            Int32 fieldNameLength = fieldText.Length - endMerge;
            string fieldName = fieldText.Substring(11, endMerge - 11);
            fieldName = fieldName.Trim();
            if (fieldName == field)
            {
                myMergeField.Select();
                app.Selection.TypeText(word);
            }
        }
    }

    // 保存パス
    doc.SaveAs(@"C:\tmp\output.docx");

    var doc_close = (_Document)doc;
    doc_close.Close();

    var applicationclose = (_Application)app;
    applicationclose.Quit();
}

画像を差し込む場合

画像の場合は、フィールドではできないので、替わりにブックマークを使用する。
Wordで、画像を差し込みたい箇所で、メニュー>挿入>ブックマーク。
C#から参照する名前(ここではIMAGE)をつけて、追加。
ブックマークなので、Word上は何の表示もない。

image.png

C#では、doc.BookmarksからブックマークのIMAGEを取得して、AddPictureで画像を差し込んでいる。

string _imagePath = @"c:\aaa.jpg";
foreach (Bookmark b in doc.Bookmarks)
   {
        if (b.Name == "IMAGE")
        {
             doc.Bookmarks["IMAGE"].Range.InlineShapes.AddPicture(_imagePath, false, true);
        }
   }

参考

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2