使用C#代码修改 Word 文档中的内容控件

在 Word 文档中,内容控件可以实现内容的动态更新与修改,为用户提供更加灵活的编辑和管理方式。借助内容控件,用户可以在指定区域中轻松插入、删除或修改内容,而不会影响文档的整体结构。

本文将介绍如何在 C# 项目中使用 Spire.Doc for .NET,对 Word 文档中的内容控件进行修改。

安装 Spire.Doc for .NET

首先,需要将 Spire.Doc for .NET 安装包中的 DLL 文件添加为 .NET 项目的引用。你可以通过下载官方安装包获取这些 DLL 文件,或者直接通过 NuGet 进行安装。

cs 复制代码
PM> Install-Package Spire.Doc

使用 C# 修改正文中的内容控件

在 Spire.Doc 中,正文区域的内容控件对应的对象类型为 StructureDocumentTag。你可以通过遍历 Section.Body 中的子对象集合,查找该类型的对象,并对其进行修改。具体步骤如下:

  1. 创建一个 Document 对象。
  2. 使用 Document.LoadFromFile() 方法加载文档。
  3. 通过 Section.Body 访问文档中某一节的正文内容。
  4. 遍历正文中的子对象集合 Body.ChildObjects,查找类型为 StructureDocumentTag 的对象。
  5. 访问 StructureDocumentTag.ChildObjects 集合,根据子对象的类型执行相应的修改操作。
  6. 使用 Document.SaveToFile() 方法保存文档。

示例代码如下:

cs 复制代码
using Spire.Doc;
using Spire.Doc.Documents;
using System.Collections.Generic;

namespace SpireDocDemo
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // 创建一个新的文档对象
            Document doc = new Document();

            // 从文件加载文档内容
            doc.LoadFromFile("Sample1.docx");

            // 获取文档的正文内容
            Body body = doc.Sections[0].Body;

            // 创建段落和表格的列表
            List<Paragraph> paragraphs = new List<Paragraph>();
            List<Table> tables = new List<Table>();
            for (int i = 0; i < body.ChildObjects.Count; i++)
            {
                // 获取文档对象
                DocumentObject documentObject = body.ChildObjects[i];

                // 如果是 StructureDocumentTag(内容控件)对象
                if (documentObject.DocumentObjectType == DocumentObjectType.StructureDocumentTag)
                {
                    StructureDocumentTag structureDocumentTag = (StructureDocumentTag)documentObject;

                    // 如果标签为 "c1" 或别名为 "c1"
                    if (structureDocumentTag.SDTProperties.Tag == "c1" || structureDocumentTag.SDTProperties.Alias == "c1")
                    {
                        for (int j = 0; j < structureDocumentTag.ChildObjects.Count; j++)
                        {
                            // 如果是段落对象
                            if (structureDocumentTag.ChildObjects[j].DocumentObjectType == DocumentObjectType.Paragraph)
                            {
                                Paragraph paragraph = (Paragraph)structureDocumentTag.ChildObjects[j];
                                paragraphs.Add(paragraph);
                            }

                            // 如果是表格对象
                            if (structureDocumentTag.ChildObjects[j].DocumentObjectType == DocumentObjectType.Table)
                            {
                                Table table = (Table)structureDocumentTag.ChildObjects[j];
                                tables.Add(table);
                            }
                        }
                    }
                }
            }

            // 修改第一个段落的文本内容
            paragraphs[0].Text = "Spire.Doc for .NET 是一个完全独立的 .NET Word 类库,无需在系统中安装 Microsoft Office。";

            // 重置第一个表格的单元格(5 行 4 列)
            tables[0].ResetCells(5, 4);

            // 将修改后的文档保存到文件
            doc.SaveToFile("ModifyBodyContentControls.docx", FileFormat.Docx2016);

            // 释放文档资源
            doc.Dispose();
        }
    }
}

使用 C# 修改段落中的内容控件

在 Spire.Doc 中,段落内的内容控件对应的对象类型为 StructureDocumentTagInline。要对其进行修改,需要遍历 Paragraph.ChildObjects 集合,查找该类型的对象,并执行相应的操作。具体步骤如下:

  1. 创建一个 Document 对象。
  2. 使用 Document.LoadFromFile() 方法加载文档。
  3. 通过 Section.Body 访问文档中某一节的正文内容。
  4. 使用 Body.Paragraphs0 获取正文中的第一个段落。
  5. 遍历段落的子对象集合 Paragraph.ChildObjects,查找类型为 StructureDocumentTagInline 的对象。
  6. 访问 StructureDocumentTagInline.ChildObjects 集合,根据子对象类型执行相应的修改操作。
  7. 使用 Document.SaveToFile() 方法保存文档。

示例代码如下:

cs 复制代码
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Collections.Generic;

namespace SpireDocDemo
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // 创建一个新的 Document 对象
            Document doc = new Document();

            // 从文件加载文档内容
            doc.LoadFromFile("Sample2.docx");

            // 获取文档的正文内容
            Body body = doc.Sections[0].Body;

            // 获取正文中的第一个段落
            Paragraph paragraph = body.Paragraphs[0];

            // 遍历段落中的子对象
            for (int i = 0; i < paragraph.ChildObjects.Count; i++)
            {
                // 判断子对象是否为 StructureDocumentTagInline(行内内容控件)
                if (paragraph.ChildObjects[i].DocumentObjectType == DocumentObjectType.StructureDocumentTagInline)
                {
                    // 将子对象转换为 StructureDocumentTagInline 类型
                    StructureDocumentTagInline structureDocumentTagInline = (StructureDocumentTagInline)paragraph.ChildObjects[i];

                    // 判断 Tag 或 Alias 是否为 "text1"
                    if (structureDocumentTagInline.SDTProperties.Tag == "text1" || structureDocumentTagInline.SDTProperties.Alias == "text1")
                    {
                        // 遍历该内容控件中的子对象
                        for (int j = 0; j < structureDocumentTagInline.ChildObjects.Count; j++)
                        {
                            // 判断子对象是否为 TextRange(文本)
                            if (structureDocumentTagInline.ChildObjects[j].DocumentObjectType == DocumentObjectType.TextRange)
                            {
                                // 转换为 TextRange 类型
                                TextRange range = (TextRange)structureDocumentTagInline.ChildObjects[j];

                                // 设置文本内容
                                range.Text = "97-2003/2007/2010/2013/2016/2019";
                            }
                        }
                    }

                    // 判断 Tag 或 Alias 是否为 "logo1"
                    if (structureDocumentTagInline.SDTProperties.Tag == "logo1" || structureDocumentTagInline.SDTProperties.Alias == "logo1")
                    {
                        // 遍历该内容控件中的子对象
                        for (int j = 0; j < structureDocumentTagInline.ChildObjects.Count; j++)
                        {
                            // 判断子对象是否为图片
                            if (structureDocumentTagInline.ChildObjects[j].DocumentObjectType == DocumentObjectType.Picture)
                            {
                                // 转换为 DocPicture 类型
                                DocPicture docPicture = (DocPicture)structureDocumentTagInline.ChildObjects[j];

                                // 加载指定图片
                                docPicture.LoadImage("Doc-NET.png");

                                // 设置图片的宽度和高度
                                docPicture.Width = 100;
                                docPicture.Height = 100;
                            }
                        }
                    }
                }
            }

            // 将修改后的文档保存为新文件
            doc.SaveToFile("ModifiedContentControlsInParagraph.docx", FileFormat.Docx2016);

            // 释放 Document 对象资源
            doc.Dispose();
        }
    }
}

使用 C# 修改包裹表格行的内容控件

在 Spire.Doc 中,表格行级别的内容控件对应的对象类型为 StructureDocumentTagRow。要对其进行修改,需要遍历 Table.ChildObjects 集合,查找该类型的对象,并执行相应的操作。具体步骤如下:

  1. 创建一个 Document 对象。
  2. 使用 Document.LoadFromFile() 方法加载文档。
  3. 通过 Section.Body 访问文档中某一节的正文内容。
  4. 使用 Body.Tables0 获取正文中的第一个表格。
  5. 遍历表格的子对象集合 Table.ChildObjects,查找类型为 StructureDocumentTagRow 的对象。
  6. 访问 StructureDocumentTagRow.Cells(表格行内容控件中的单元格集合),并对单元格内容进行相应修改。
  7. 使用 Document.SaveToFile() 方法保存文档。

示例代码如下:

cs 复制代码
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

namespace SpireDocDemo
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // 创建一个新的文档对象
            Document doc = new Document();

            // 从文件加载文档
            doc.LoadFromFile("Sample3.docx");

            // 获取文档的正文内容
            Body body = doc.Sections[0].Body;

            // 获取第一个表格
            Table table = (Table)body.Tables[0];

            // 遍历表格中的子对象
            for (int i = 0; i < table.ChildObjects.Count; i++)
            {
                // 判断子对象是否为 StructureDocumentTagRow(表格行内容控件)
                if (table.ChildObjects[i].DocumentObjectType == DocumentObjectType.StructureDocumentTagRow)
                {
                    // 转换为 StructureDocumentTagRow 对象
                    StructureDocumentTagRow structureDocumentTagRow = (StructureDocumentTagRow)table.ChildObjects[i];

                    // 判断 Tag 或 Alias 是否为 "row1"
                    if (structureDocumentTagRow.SDTProperties.Tag == "row1" || structureDocumentTagRow.SDTProperties.Alias == "row1")
                    {
                        // 清除该单元格中的段落内容
                        structureDocumentTagRow.Cells[0].Paragraphs.Clear();

                        // 在单元格中添加段落并设置文本
                        TextRange textRange = structureDocumentTagRow.Cells[0].AddParagraph().AppendText("Arts");
                        textRange.CharacterFormat.TextColor = System.Drawing.Color.Blue;
                    }
                }
            }

            // 将修改后的文档保存到文件
            doc.SaveToFile("ModifiedTableRowContentControl.docx", FileFormat.Docx2016);

            // 释放文档资源
            doc.Dispose();
        }
    }
}

使用 C# 修改包裹表格单元格的内容控件

在 Spire.Doc 中,表格单元格中的内容控件对应的对象类型为 StructureDocumentTagCell。要对其进行修改,需要遍历 TableRow.ChildObjects 集合,查找该类型的对象,并对其执行相应操作。具体步骤如下:

  1. 创建一个 Document 对象。
  2. 使用 Document.LoadFromFile() 方法加载文档。
  3. 通过 Section.Body 获取文档中某一节的正文内容。
  4. 使用 Body.Tables0 获取正文中的第一个表格。
  5. 遍历表格行集合 Table.Rows,逐一获取每个 TableRow 对象。
  6. 遍历每一行的子对象集合 TableRow.ChildObjects,查找类型为 StructureDocumentTagCell 的对象。
  7. 访问 StructureDocumentTagCell 中的段落集合,并对内容进行相应修改。
  8. 使用 Document.SaveToFile() 方法保存文档。

示例代码如下:

cs 复制代码
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

namespace SpireDocDemo
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // 创建一个新的文档对象
            Document doc = new Document();

            // 从文件加载文档
            doc.LoadFromFile("Sample4.docx");

            // 获取文档的正文内容
            Body body = doc.Sections[0].Body;

            // 获取文档中的第一个表格
            Table table = (Table)body.Tables[0];

            // 遍历表格的每一行
            for (int i = 0; i < table.Rows.Count; i++)
            {
                // 遍历每一行中的子对象
                for (int j = 0; j < table.Rows[i].ChildObjects.Count; j++)
                {
                    // 判断子对象是否为 StructureDocumentTagCell(单元格内容控件)
                    if (table.Rows[i].ChildObjects[j].DocumentObjectType == DocumentObjectType.StructureDocumentTagCell)
                    {
                        // 转换为 StructureDocumentTagCell 类型
                        StructureDocumentTagCell structureDocumentTagCell = (StructureDocumentTagCell)table.Rows[i].ChildObjects[j];

                        // 判断 Tag 或 Alias 是否为 "cell1"
                        if (structureDocumentTagCell.SDTProperties.Tag == "cell1" || structureDocumentTagCell.SDTProperties.Alias == "cell1")
                        {
                            // 清除单元格中的段落内容
                            structureDocumentTagCell.Paragraphs.Clear();

                            // 添加新的段落并设置文本
                            TextRange textRange = structureDocumentTagCell.AddParagraph().AppendText("92");
                            textRange.CharacterFormat.TextColor = System.Drawing.Color.Blue;
                        }
                    }
                }
            }

            // 将修改后的文档保存为新文件
            doc.SaveToFile("ModifiedTableCellContentControl.docx", FileFormat.Docx2016);

            // 释放文档对象资源
            doc.Dispose();
        }
    }
}

使用 C# 修改表格单元格内的内容控件

本示例演示如何修改表格单元格中段落内的内容控件。需要先获取单元格中的段落集合 TableCell.Paragraphs,然后遍历每个段落的子对象集合 Paragraph.ChildObjects,查找类型为 StructureDocumentTagInline 的对象,并对其进行相应修改。具体步骤如下:

  1. 创建一个 Document 对象。
  2. 使用 Document.LoadFromFile() 方法加载文档。
  3. 通过 Section.Body 获取文档中某一节的正文内容。
  4. 使用 Body.Tables0 获取正文中的第一个表格。
  5. 遍历表格行集合 Table.Rows,逐一获取每个 TableRow 对象。
  6. 遍历每一行中的单元格集合 TableRow.Cells,获取每个 TableCell 对象。
  7. 遍历单元格中的段落集合 TableCell.Paragraphs,获取每个 Paragraph 对象。
  8. 遍历段落的子对象集合 Paragraph.ChildObjects,查找类型为 StructureDocumentTagInline 的对象。
  9. 访问 StructureDocumentTagInline 的 ChildObjects 集合,根据子对象类型执行相应的修改操作。
  10. 使用 Document.SaveToFile() 方法保存文档。

示例代码如下:

cs 复制代码
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

namespace SpireDocDemo
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // 创建一个新的 Document 对象
            Document doc = new Document();

            // 从文件加载文档内容
            doc.LoadFromFile("Sample5.docx");

            // 获取文档的正文内容
            Body body = doc.Sections[0].Body;

            // 获取第一个表格
            Table table = (Table)body.Tables[0];

            // 遍历表格的每一行
            for (int r = 0; r < table.Rows.Count; r++)
            {
                // 遍历每一行中的单元格
                for (int c = 0; c < table.Rows[r].Cells.Count; c++)
                {
                    // 遍历单元格中的段落
                    for (int p = 0; p < table.Rows[r].Cells[c].Paragraphs.Count; p++)
                    {
                        // 获取段落对象
                        Paragraph paragraph = table.Rows[r].Cells[c].Paragraphs[p];

                        // 遍历段落中的子对象
                        for (int i = 0; i < paragraph.ChildObjects.Count; i++)
                        {
                            // 判断子对象是否为 StructureDocumentTagInline(行内内容控件)
                            if (paragraph.ChildObjects[i].DocumentObjectType == DocumentObjectType.StructureDocumentTagInline)
                            {
                                // 转换为 StructureDocumentTagInline 对象
                                StructureDocumentTagInline structureDocumentTagInline = (StructureDocumentTagInline)paragraph.ChildObjects[i];

                                // 判断 Tag 或 Alias 是否为 "test1"
                                if (structureDocumentTagInline.SDTProperties.Tag == "test1" || structureDocumentTagInline.SDTProperties.Alias == "test1")
                                {
                                    // 遍历该内容控件中的子对象
                                    for (int j = 0; j < structureDocumentTagInline.ChildObjects.Count; j++)
                                    {
                                        // 判断子对象是否为 TextRange(文本)
                                        if (structureDocumentTagInline.ChildObjects[j].DocumentObjectType == DocumentObjectType.TextRange)
                                        {
                                            // 转换为 TextRange 对象
                                            TextRange textRange = (TextRange)structureDocumentTagInline.ChildObjects[j];

                                            // 设置文本内容
                                            textRange.Text = "89";

                                            // 设置文本颜色
                                            textRange.CharacterFormat.TextColor = System.Drawing.Color.Blue;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // 将修改后的文档保存为新文件
            doc.SaveToFile("ModifiedContentControlInParagraphOfTableCell.docx", FileFormat.Docx2016);

            // 释放 Document 对象资源
            doc.Dispose();
        }
    }
}

申请临时许可证

如果您希望去除生成文档中的评估提示信息,或解除功能限制,可以申请一个为期 30 天的试用许可证。

相关推荐
Scott9999HH1 小时前
【IIoT流量实战】蒸汽管道阀门全关却仍有流量?用 Python 实现涡街信号 FFT 频谱分析与温压全补偿积算网关,深度拆解靠谱的涡街流量计厂家硬核技术标准
开发语言·python
EIP低代码平台1 小时前
EIP 低代码平台 - 角色维护
低代码·c#·权限·工作流·netcore
码智社2 小时前
AES加密原理详解及Java实现加解密实战
java·开发语言
AI云海2 小时前
python 列表、元组、集合和字典
开发语言·python
Am-Chestnuts2 小时前
Kimi长回答批量导出Word:DS随心转实践
word
萧瑟余晖3 小时前
JDK 26 新特性详解
java·开发语言
马优晨4 小时前
Freemarker 完整讲解(后端 Java 模板引擎)
java·开发语言·freemarker·freemarker 完整讲解·freemarker模板引擎
人邮异步社区6 小时前
怎么把C语言学到精通?
c语言·开发语言
曹牧6 小时前
Word:更改列表级别
word
心平气和量大福大6 小时前
C#-WPF-控件-TextBox 数据绑定
开发语言·c#·wpf