- using Spire.Doc;
- using Spire.Doc.Documents;
- using Spire.Doc.Fields;
- namespace ReplaceTextWithTable_Doc
- {
- class Program
- {
- static void Main(string[] args)
- {
- //实例化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);
- System.Diagnostics.Process.Start("result.doc");
-
- }
- }
- }