当前位置:首页 > C# 插入、删除Word书签
【示例3】插入表格到书签所在段落
C#
using Spire.Doc;
using Spire.Doc.Documents; using System.Data;
namespace InsertTableToBookmark_Doc {
class Program {
static void Main(string[] args) {
//创建文档,加载文件
Document doc = new Document(); doc.LoadFromFile(\);
//创建Table对象
Table table = new Table(doc, true);
//创建模拟数据
DataTable dt = new DataTable(); dt.Columns.Add(\, typeof(string)); dt.Columns.Add(\, typeof(string)); dt.Columns.Add(\, typeof(string));
dt.Columns.Add(\, typeof(string)); dt.Rows.Add(new string[] { \,\, \, \ });
dt.Rows.Add(new string[] { \, \, \, \ }); dt.Rows.Add(new string[] { \, \, \, \ }); dt.Rows.Add(new string[] { \, \, \, \ });
//将数据填充至表格
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(\);
//将表格添加至TextBodyPart
TextBodyPart part = navigator.GetBookmarkContent(); part.BodyItems.Add(table);
//替换书签内容
navigator.ReplaceBookmarkContent(part);
//保存并打开文件
doc.SaveToFile(\, FileFormat.Docx2013);
System.Diagnostics.Process.Start(\); } } }
表格插入效果:
【示例4】删除书签
C#
using Spire.Doc;
using Spire.Doc.Documents;
namespace Removing {
class Program {
static void Main(string[] args) {
//实例化Document类,加载文档 Document doc = new Document(); doc.LoadFromFile(\);
//创建BookmarksNavigator实例
BookmarksNavigator navigator = new BookmarksNavigator(doc);
//指向特定的书签
navigator.MoveToBookmark(\);
//删除书签中的内容
navigator.DeleteBookmarkContent(false);
//删除书签
doc.Bookmarks.Remove(doc.Bookmarks.FindByName(\));
//保存并打开文档
doc.SaveToFile(\, FileFormat.Docx); System.Diagnostics.Process.Start(\); } } }
测试结果: 测试文档如下
删除书签后:
以上内容为本次“C#操作Word书签的方法”介绍如需转载,请注明出处。
共分享92篇相关文档