1. Create a Word Template.
2. Create a console application
Add refrence to Microsoft Word 15.0 Object Library.
using Microsoft.Office.Interop.Word;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace wordTemplateTest
{
class Program
{
static void Main(string[] args)
{//OBJECT OF MISSING "NULL VALUE"
Object oMissing = System.Reflection.Missing.Value;
Object oTemplatePath = "D:\\Git\\wordTemplateTest\\wordTemplateTest\\Template\\Template.docx";
Application wordApp = new Application();
Document wordDoc = new Document();
wordDoc = wordApp.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);
//在書籤處插入文字
object oStart = "書籤";//word中的書籤名
Range range = wordDoc.Bookmarks.get_Item(ref oStart).Range;//表格插入位置
range.Text = "這裏是您要輸入的內容";//在書籤處插入文字內容
foreach (Bookmark r in wordDoc.Bookmarks)
{
//在標籤處插入圖片
if(r.Name=="picture")
{
r.Range.InlineShapes.AddPicture("D:\\Git\\wordTemplateTest\\wordTemplateTest\\Template\\3.jpg");
}
}
foreach (Field myMergeField in wordDoc.Fields)
{
Range rngFieldCode = myMergeField.Code;
String fieldText = rngFieldCode.Text;
// ONLY GETTING THE MAILMERGE FIELDS
if (fieldText.StartsWith(" MERGEFIELD"))
{
// THE TEXT COMES IN THE FORMAT OF
// MERGEFIELD MyFieldName \\* MERGEFORMAT
// THIS HAS TO BE EDITED TO GET ONLY THE FIELDNAME "MyFieldName"
Int32 endMerge = fieldText.IndexOf("\\");
Int32 fieldNameLength = fieldText.Length - endMerge;
String fieldName = fieldText.Substring(11, endMerge - 11);
// GIVES THE FIELDNAMES AS THE USER HAD ENTERED IN .dot FILE
fieldName = fieldName.Trim();
// **** FIELD REPLACEMENT IMPLEMENTATION GOES HERE ****//
// THE PROGRAMMER CAN HAVE HIS OWN IMPLEMENTATIONS HERE
if (fieldName == "Name")
{
myMergeField.Select();
wordApp.Selection.TypeText("test");
}
}
}
wordDoc.SaveAs("D:\\Git\\wordTemplateTest\\wordTemplateTest\\Template\\myfile.doc");
wordApp.Documents.Open("D:\\Git\\wordTemplateTest\\wordTemplateTest\\Template\\myfile.doc");
wordApp.Application.Quit();
}
}
}