Word 书签可以帮助程序员快速定位到文档指定地点,本教程展示如何使用Spire.Doc获取某一个书签,并在书签现有内容的后面插入表格。
C#
//加载模板文档
Document doc = new Document();
doc.LoadFromFile(@"C:\Users\Administrator\Desktop\employee.docx");
//创建Table对象
Table table = new Table(doc,true);
//创建模拟数据
DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(string));
dt.Columns.Add("name", typeof(string));
dt.Columns.Add("job", typeof(string));
dt.Columns.Add("email", typeof(string));
dt.Columns.Add("salary", typeof(string));
dt.Rows.Add(new string[] { "员工编号", "姓名", "职位", "邮箱", "电话" });
dt.Rows.Add(new string[] { "0241", "王浩然", "销售", "wang_hao_ran @outlook.com", "137****2211" });
dt.Rows.Add(new string[] { "0242", "李向阳", "销售", "xiangyang @outlook.com", "159****5470" });
dt.Rows.Add(new string[] { "0243", "闫佳强", "经理", "yjq1988 @gmail.com", "182****6541" });
//将数据填充至表格
table.ResetCells(dt.Rows.Count, dt.Columns.Count);
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
table.Rows[i].Cells[j].AddParagraph().AppendText(dt.Rows[i][j].ToString());
}
}
//获取指定书签位置
BookmarksNavigator navigator = new BookmarksNavigator(doc);
navigator.MoveToBookmark("employee_table");
//将表格添加至TextBodyPart
TextBodyPart part = navigator.GetBookmarkContent();
part.BodyItems.Add(table);
//替换书签内容
navigator.ReplaceBookmarkContent(part);
//保存文件
doc.SaveToFile("output.docx", FileFormat.Docx2013);
VB.NET
'加载模板文档
Dim doc As Document = New Document
doc.LoadFromFile("C:\Users\Administrator\Desktop\employee.docx")
'创建Table对象
Dim table As Table = New Table(doc, true)
'创建模拟数据
Dim dt As DataTable = New DataTable
dt.Columns.Add("id", GetType(System.String))
dt.Columns.Add("name", GetType(System.String))
dt.Columns.Add("job", GetType(System.String))
dt.Columns.Add("email", GetType(System.String))
dt.Columns.Add("salary", GetType(System.String))
dt.Rows.Add(New String() {"员工编号", "姓名", "职位", "邮箱", "电话"})
dt.Rows.Add(New String() {"0241", "王浩然", "销售", "wang_hao_ran @outlook.com", "137****2211"})
dt.Rows.Add(New String() {"0242", "李向阳", "销售", "xiangyang @outlook.com", "159****5470"})
dt.Rows.Add(New String() {"0243", "闫佳强", "经理", "yjq1988 @gmail.com", "182****6541"})
'将数据填充至表格
table.ResetCells(dt.Rows.Count, dt.Columns.Count)
Dim i As Integer = 0
Do While (i < dt.Rows.Count)
Dim j As Integer = 0
Do While (j < dt.Columns.Count)
table.Rows(i).Cells(j).AddParagraph.AppendText(dt.Rows(i)(j).ToString)
j = (j + 1)
Loop
i = (i + 1)
Loop
'获取指定书签位置
Dim navigator As BookmarksNavigator = New BookmarksNavigator(doc)
navigator.MoveToBookmark("employee_table")
'将表格添加至TextBodyPart
Dim part As TextBodyPart = navigator.GetBookmarkContent
part.BodyItems.Add(table)
'替换书签内容
navigator.ReplaceBookmarkContent(part)
'保存文件
doc.SaveToFile("output.docx", FileFormat.Docx2013)
效果截图: