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)
效果截图: