首先設置word模板,能夠點擊某個單元格插入書籤數組
插入方法:鼠標點擊word文件某處,而後 插入--書籤 便可ui
//關鍵代碼以下……………………code
string tmppath = Server.MapPath("~/Template.doc"); Document doc = new Document(tmppath); //載入模板 //使用書籤 if (doc.Range.Bookmarks["mark"] != null) { //Bookmark mark = doc.Range.Bookmarks["mark"];//根據書籤名稱獲取書籤 //mark.Text = "sean"; } //不使用書籤 經過移動單元格 來添加值 DocumentBuilder builder = new DocumentBuilder(doc); //設置單元格內容對齊方式 builder.ParagraphFormat.Alignment = ParagraphAlignment.Left; builder.MoveToCell(0, 2, 3,0); //tableIndex,rowIndex,columnIndex,characterIndex 初始索引0 builder.Write("chang"); doc.Save("demo.doc", SaveFormat.Doc, SaveType.OpenInWord, Response); //保存爲doc,並打開 //doc.Save(HttpContext.Current.Server.MapPath(savePath), SaveFormat.Doc);//直接保存文件 //PS: 在實際使用過程當中發現若是表格都在word模板第一頁的時候,咱們能夠使用經過更改moveToCell方法第一個參數tableIndex來填寫具體哪一個表,可是當模板有若干頁時, 經過更改方法第一個參數值直接報錯(超出表索引) 在網上找了半天,最終發現了一個算是很麻煩的方法:模板插入域(插入--文檔部件--域--類別選擇郵件合併點擊MergeField輸入名稱),而後Aspose.Words提供一個方法: doc.MailMerge.Execute(string[]fieldNames,object[]values) 及把模板中的域名稱以及數組對應數據分別組合一個數組,經過該方法能夠把數據插入對應域上。這個方法 適用於模板中單元格相對比較少,若是太多的話模板維護起來很麻煩。