Spire.Doc支持查找替換Word中的文本、圖片等。前文介紹瞭如何用文檔、文本替換Word文本,本篇文章將介紹用圖片、表格替換Word文本的方法。
用圖片替換Word文本
測試文檔:
代碼如下:
//實例化Document類的對象,並加載測試文檔 Document doc = new Document(); doc.LoadFromFile("testfile.docx"); //加載替換的圖片 Image image = Image.FromFile("g.png"); //獲取第一個section Section sec= doc.Sections[0]; //查找文檔中的指定文本內容 TextSelection[] selections = doc.FindAllString("Google", true, true); int index = 0; TextRange range = null; //遍歷文檔,移除文本內容,插入圖片 foreach (TextSelection selection in selections) { DocPicture pic = new DocPicture(doc); pic.LoadImage(image); range = selection.GetAsOneRange(); index = range.OwnerParagraph.ChildObjects.IndexOf(range); range.OwnerParagraph.ChildObjects.Insert(index, pic); range.OwnerParagraph.ChildObjects.Remove(range); } //保存文檔 doc.SaveToFile("result.docx", FileFormat.Docx);
替換結果:
用表格替換Word文本
代碼如下:
//實例化Document類的對象,並加載測試文檔 Document doc = new Document(); doc.LoadFromFile("test.docx"); //查找關鍵字符串文本 Section section = doc.Sections[0]; TextSelection selection = doc.FindString("參考附錄", true, true); //獲取關鍵字符串所在段落的索引 TextRange range = selection.GetAsOneRange(); Paragraph paragraph = range.OwnerParagraph; Body body = paragraph.OwnerTextBody; int index = body.ChildObjects.IndexOf(paragraph); //添加一個兩行三列的表格 Table table = section.AddTable(true); table.ResetCells(2, 3); range = table[0, 0].AddParagraph().AppendText("管號(McFarland)"); range = table[0, 1].AddParagraph().AppendText("0.5"); range = table[0, 2].AddParagraph().AppendText("1"); range = table[1, 0].AddParagraph().AppendText("0.25%BaCl2(ml)"); range = table[1, 1].AddParagraph().AppendText("0.2"); range = table[1, 2].AddParagraph().AppendText("0.4"); //移除段落,插入表格 body.ChildObjects.Remove(paragraph); body.ChildObjects.Insert(index, table); //保存文檔 doc.SaveToFile("result.doc", FileFormat.Doc);
替換結果: