C# 操作Word书签(二)——插入图片、表格到书签;读取、替换书签

概要

书签的设置可以帮助我们快速的定位某段文字,使用起来很方便,也很节省时间。在前一篇文章“C# 如何添加/删除Word书签”中介绍了插入、删除书签的方法,本篇文章将对C# 操作Word书签的功能做进一步介绍。示例内容将包含以下要点:

  • 在现有书签位置插入图片
  • 在现有书签位置插入表格
  • 读取书签位置的文档内容
  • 替换现有书签位置内容

 

使用工具

ps:下载安装该类库后,注意添加引用Spire.Doc.dl到项目程序,dll文件可在安装路径的Bin文件夹中获取。

示例代码(供参考)

测试文档如下:

 

 

【示例1】 在现有书签位置插入图片

步骤 1: 添加using指令

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;

步骤 2 :主要代码段

//创建实例,加载文档
Document document = new Document();
document.LoadFromFile("test.docx");

//实例化BookmarksNavigator类,指定需要添加图片的书签“Bookmark1”
BookmarksNavigator bn = new BookmarksNavigator(document);
bn.MoveToBookmark("Bookmark1", true, true);

//添加段落,加载图片并插入到段落
Section section0 = document.AddSection();
Paragraph paragraph = section0.AddParagraph();
Image image = Image.FromFile("img.png");
DocPicture picture = paragraph.AppendPicture(image);
bn.InsertParagraph(paragraph);
document.Sections.Remove(section0);

//保存文档并打开
string output = "result.docx";
document.SaveToFile(output, FileFormat.Docx);
System.Diagnostics.Process.Start(output);

图片插入效果:

 

全部代码:

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;

namespace InsertImgToBookmark_Doc
{
    class Program
    {
        static void Main(string[] args)
        {
            //创建实例,加载文档
            Document document = new Document();
            document.LoadFromFile("test.docx");

            //实例化BookmarksNavigator类,指定需要添加图片的书签“Bookmark1”
            BookmarksNavigator bn = new BookmarksNavigator(document);
            bn.MoveToBookmark("Bookmark1", true, true);

            //添加段落,加载图片并插入到段落
            Section section0 = document.AddSection();
            Paragraph paragraph = section0.AddParagraph();
            Image image = Image.FromFile("img.png");
            DocPicture picture = paragraph.AppendPicture(image);
            bn.InsertParagraph(paragraph);
            document.Sections.Remove(section0);

            //保存文档并打开
            string output = "result.docx";
            document.SaveToFile(output, FileFormat.Docx);
            System.Diagnostics.Process.Start(output);
        }
    }
}
View Code

 

 【示例 2】在现有书签位置插入表格

步骤 1:添加using指令

using Spire.Doc;
using Spire.Doc.Documents;
using System.Data;

步骤 2 :创建文档,加载文件

Document doc = new Document();
doc.LoadFromFile("test.docx");

步骤 3 :创建表格

//创建Table对象
Table table = new Table(doc, true);

//创建模拟数据
DataTable dt = new DataTable();
dt.Columns.Add("PI", typeof(string));
dt.Columns.Add("Type", typeof(string));
dt.Columns.Add("Nov.", typeof(string));
dt.Columns.Add("YTD", typeof(string));                     
dt.Rows.Add(new string[] { "PI","Type", "Nov.", "YTD" });
dt.Rows.Add(new string[] { "1", "BAIC EC-Series", "15.719", "64.910" });
dt.Rows.Add(new string[] { "2", "Tesla Model S", "3.889", "46.951" });
dt.Rows.Add(new string[] { "3", "Nissan Leaf", "2.817", "46.423" });

//将数据填充至表格
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());
    }
}

步骤 4 :插入表格到书签位置

//获取指定书签位置
BookmarksNavigator navigator = new BookmarksNavigator(doc);
navigator.MoveToBookmark("origin2");

//将表格添加至TextBodyPart
TextBodyPart part = navigator.GetBookmarkContent();
part.BodyItems.Add(table);
//替换原有书签内容
navigator.ReplaceBookmarkContent(part);

步骤 5 :保存文件

//保存并打开文件
doc.SaveToFile("output.docx", FileFormat.Docx2013);
System.Diagnostics.Process.Start("output.docx");

 

 表格插入效果:

全部代码:

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("test.docx");

            //创建Table对象
            Table table = new Table(doc, true);

            //创建模拟数据
            DataTable dt = new DataTable();
            dt.Columns.Add("PI", typeof(string));
            dt.Columns.Add("Type", typeof(string));
            dt.Columns.Add("Nov.", typeof(string));
            dt.Columns.Add("YTD", typeof(string));                     
            dt.Rows.Add(new string[] { "PI","Type", "Nov.", "YTD" });
            dt.Rows.Add(new string[] { "1", "BAIC EC-Series", "15.719", "64.910" });
            dt.Rows.Add(new string[] { "2", "Tesla Model S", "3.889", "46.951" });
            dt.Rows.Add(new string[] { "3", "Nissan Leaf", "2.817", "46.423" });

            //将数据填充至表格
            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("origin2");

            //将表格添加至TextBodyPart
            TextBodyPart part = navigator.GetBookmarkContent();
            part.BodyItems.Add(table);

            //替换书签内容
            navigator.ReplaceBookmarkContent(part);

            //保存并打开文件
            doc.SaveToFile("output.docx", FileFormat.Docx2013);
            System.Diagnostics.Process.Start("output.docx");
        }
    }
}
View Code

 

【示例3】读取书签位置的内容

步骤 1 :添加using指令

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System;

步骤 2 :获取书签位置的内容

//初始化BookmarkNavigator类对象
BookmarksNavigator navigator = new BookmarksNavigator(doc);
//定位到指定书签位置,获取书签位置的文档内容
navigator.MoveToBookmark("bookmark1");
TextBodyPart textBodyPart = navigator.GetBookmarkContent();

步骤 3 :读取书签内容

//遍历书签内容中的子项目,并将文本信息提取至string类型变量中
string text = null;
foreach (var item in textBodyPart.BodyItems)
{
    if (item is Paragraph)
    {
        foreach (var childObject in (item as Paragraph).ChildObjects)
        {
            if (childObject is TextRange)
            {
                text += (childObject as TextRange).Text;
            }
        }
    }
}
//控制台输出文本
Console.WriteLine(text);
Console.ReadLine();

 

 读取结果:

全部代码:

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System;

namespace GetTextOfBookmark_Doc
{
    class Program
    {
        static void Main(string[] args)
        {
            //实例化Document类,加载测试文档
            Document doc = new Document();
            doc.LoadFromFile("test.docx");

            //初始化BookmarkNavigator类对象
            BookmarksNavigator navigator = new BookmarksNavigator(doc);
            //定位到指定书签位置,获取书签位置的文档内容
            navigator.MoveToBookmark("bookmark1");
            TextBodyPart textBodyPart = navigator.GetBookmarkContent();

            //遍历书签内容中的子项目,并将文本信息提取至string类型变量中
            string text = null;
            foreach (var item in textBodyPart.BodyItems)
            {
                if (item is Paragraph)
                {
                    foreach (var childObject in (item as Paragraph).ChildObjects)
                    {
                        if (childObject is TextRange)
                        {
                            text += (childObject as TextRange).Text;
                        }
                    }
                }
            }
            //控制台输出文本
            Console.WriteLine(text);
            Console.ReadLine();
        }
    }
}
View Code

 

【示例4】替换现有书签内容

步骤 1 :添加using指令

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

步骤 2 :加载文档

Document document = new Document();
document.LoadFromFile("test.docx");

步骤 3 :添加段落及文字

Section sec = document.AddSection();//添加section
sec.AddParagraph().AppendText("Welcome Back, \n My Friend!"); //添加段落到section,并添加字符串内容

步骤 4 :获取段落

//获取段落内容 
ParagraphBase firstReplacementParagraph = sec.Paragraphs[0].Items.FirstItem as ParagraphBase;
ParagraphBase lastReplacementParagraph = sec.Paragraphs[sec.Paragraphs.Count - 1].Items.LastItem as ParagraphBase;
//实例化类TextBodySelection和TextBodyPart
TextBodySelection selection = new TextBodySelection(firstReplacementParagraph, lastReplacementParagraph);
TextBodyPart part = new TextBodyPart(selection);

步骤 5 :替换书签内容

BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document);//实例化BookmarksNavigator类 
bookmarkNavigator.MoveToBookmark("bookmark1", true, true);//定位到书签“bookmark1”所在段落的位置
bookmarkNavigator.DeleteBookmarkContent(true);//删除原有书签位置的内容
bookmarkNavigator.ReplaceBookmarkContent(part, true, true);//用新添加段落的内容替换掉原书签的内容并保留格式
document.Sections.Remove(sec); //移除section

步骤 6 :保存文档

//保存文档并打开
document.SaveToFile("替换书签.docx");
System.Diagnostics.Process.Start("替换书签.docx");

 

替换效果:

全部代码:

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

namespace EditOrReplaceBookmark_Doc
{
    class Program
    {
        static void Main(string[] args)
        {
            //创建Document类实例,加载文档 
            Document document = new Document();
            document.LoadFromFile("test.docx");

            Section sec = document.AddSection();//添加section
            sec.AddParagraph().AppendText("Welcome Back, \n My Friend!"); //添加段落到section,并添加字符串内容

            //获取段落内容 
            ParagraphBase firstReplacementParagraph = sec.Paragraphs[0].Items.FirstItem as ParagraphBase;
            ParagraphBase lastReplacementParagraph = sec.Paragraphs[sec.Paragraphs.Count - 1].Items.LastItem as ParagraphBase;
            //实例化类TextBodySelection和TextBodyPart
            TextBodySelection selection = new TextBodySelection(firstReplacementParagraph, lastReplacementParagraph);
            TextBodyPart part = new TextBodyPart(selection);

            BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document);//实例化BookmarksNavigator类 
            bookmarkNavigator.MoveToBookmark("bookmark1", true, true);//定位到书签“bookmark1”所在段落的位置
            bookmarkNavigator.DeleteBookmarkContent(true);//删除原有书签位置的内容
            bookmarkNavigator.ReplaceBookmarkContent(part, true, true);//用新添加段落的内容替换掉原书签的内容并保留格式            
            document.Sections.Remove(sec); //移除section

            //保存文档并打开
            document.SaveToFile("替换书签.docx");
            System.Diagnostics.Process.Start("替换书签.docx");
        }
    }
}
View Code

 

以上是本次关于C# 操作Word书签功能的补充介绍,如需转载,请注明出处。

(本文完)

 

posted @ 2018-07-19 15:26  E-iceblue  阅读(7983)  评论(3编辑  收藏  举报