一、制作word模板
1、插入文檔部件,用於替換文檔中固定字段

插入文檔部件效果

2、插入書簽

要先在文檔中設置標簽可見(文件--選項--高級--勾選顯示書簽),才能看到插入標簽效果
二、獲取模板
private string _templatePath = ""; //模板路徑 private object _filePath = ""; //生成中間文檔路徑 private string _savePath = ""; //保存生成文檔路徑 private object _missing = System.Reflection.Missing.Value; File.Copy(_templatePath.ToString(), _savePath.ToString(), true); //將文件復制到結果文檔中 var doc = new Document(_savePath); var builder = new DocumentBuilder(doc);
doc.Save(_savePath);//保存文檔
三、替換文檔中域文字
while (builder.MoveToMergeField("companyName"))
{
builder.Write("文檔編輯"); //替換公司名稱
}
四、跳轉指定書簽位置
var bookmark = doc.Range.Bookmarks["position"];
bookmark2.Text = "";//替換掉書簽名稱
builder.MoveToBookmark("position");//跳轉指定書簽
builder.Write("跳轉到書簽寫了一段話");

五、段落設置
插入Html代碼,可設置文檔標題(1-6號標題均可),有一些弊端:某些Html代碼不識別
builder.InsertHtml("<h3>標題3</h3>");
設置段落對齊方式
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center; //水平居中對齊 builder.ParagraphFormat.Alignment = ParagraphAlignment.Left; //平居左對齊 builder.ParagraphFormat.Alignment = ParagraphAlignment.Right; //平居右對齊
段落字號、加粗
builder.Font.Size = 12;//字體12磅
builder.Bold = true;//字體加粗
builder.Writeln("字體12磅,加粗");
builder.Bold = false;
插入圖片
builder.InsertImage(pictureUrl, RelativeHorizontalPosition.Page, 10, RelativeVerticalPosition.Margin, 5, 400, 100, WrapType.None);//pictureUrl圖片路徑
插入分頁
builder.InsertBreak(BreakType.PageBreak); //插入分頁
