冰蓝科技
|
028-81705109
|
|
微信扫一扫
|

Spire.Cloud 纯前端文档控件

Excel 是组织和分析数据的强大工具,但默认的黑白电子表格可能会让人难以一眼识别关键信息。通过在特定单元格中添加填充色、渐变色或图案,可以突出显示重要数据,区分不同类别的信息,使电子表格更具视觉吸引力。本文将介绍如何使用 Spire.XLS for Python 在 Excel 单元格中设置填充色、渐变色或图案。

安装 Spire.XLS for Python

此教程需要 Spire.XLS for Python 和 plum-dispatch v1.7.4。您可以通过以下 pip 命令将它们轻松安装到 Windows 中。

pip install Spire.XLS

如果您不确定如何安装,请参考: 如何在 Windows 中安装 Spire.XLS for Python

Python 为 Excel 单元格添加填充颜色

Spire.XLS for Python 提供的 CellRange.Style.Color 属性可为 Excel 单元格添加纯色背景。具体步骤如下:

  • Python
from spire.xls import *
from spire.xls.common import *

inputFile = "库存.xlsx"
outputFile = "单元格颜色.xlsx"

# 创建Workbook对象
workbook = Workbook()

# 加载Excel文件
workbook.LoadFromFile(inputFile)

# 获取第一张工作表
worksheet = workbook.Worksheets[0]

# 为单元格或单元格区域设置填充颜色
worksheet.Range["A1:G1"].Style.Color = Color.get_Green()
worksheet.Range["A6"].Style.Color = Color.get_Yellow()

# 保存结果文件
workbook.SaveToFile(outputFile, ExcelVersion.Version2016)
workbook.Dispose()

Python 在 Excel 单元格中添加填充颜色、渐变、图案

Python 为 Excel 单元格添加渐变填充

要在 Excel 中应用渐变填充,首先需要将单元格填充样式类型设置为渐变,然后指定渐变填充的两种颜色和阴影样式。具体步骤如下:

  • Python
from spire.xls import *
from spire.xls.common import *

inputFile = "库存.xlsx"
outputFile = "单元格渐变色.xlsx"

# 创建Workbook对象
workbook = Workbook()

# 加载Excel文件
workbook.LoadFromFile(inputFile)

# 获取第一张工作表
worksheet = workbook.Worksheets[0]

# 获取指定区域的单元格样式
cellStyle = worksheet.Range["A1:A15"].Style

# 将单元格填充图案类型设置为渐变
cellStyle.Interior.FillPattern  = ExcelPatternType.Gradient

# 设置渐变填充的背景色和前景色
cellStyle.Interior.Gradient.BackColor = Color.get_SkyBlue()
cellStyle.Interior.Gradient.ForeColor = Color.get_White()

# 设置渐变阴影样式
cellStyle.Interior.Gradient.GradientStyle = GradientStyleType.From_Center

# 保存结果文件
workbook.SaveToFile(outputFile, ExcelVersion.Version2016)
workbook.Dispose()

Python 在 Excel 单元格中添加填充颜色、渐变、图案

Python 为 Excel 单元格添加填充图案

您还可以通过 CellRange.Style.FillPattern 属性为特定单元格添加预定义的图案,如不同样式的条纹、圆点和剖面线。具体步骤如下:

  • Python
from spire.xls import * 
from spire.xls.common import *

inputFile = "库存.xlsx"
outputFile = "单元格图案.xlsx"

# 创建Workbook对象
workbook = Workbook()

# 加载Excel文件
workbook.LoadFromFile(inputFile)

# 获取第一张工作表
worksheet = workbook.Worksheets[0]

# 为单元格或单元格区域设置单元格填充图案
worksheet.Range["A6:E10"].Style.FillPattern = ExcelPatternType.Percent125Gray
worksheet.Range["G2"].Style.FillPattern = ExcelPatternType.ThinDiagonalStripe

# 保存结果文件
workbook.SaveToFile(outputFile, ExcelVersion.Version2016)
workbook.Dispose()

Python 在 Excel 单元格中添加填充颜色、渐变、图案

申请临时 License

如果您希望删除结果文档中的评估消息,或者摆脱功能限制,请该Email地址已收到反垃圾邮件插件保护。要显示它您需要在浏览器中启用JavaScript。获取有效期 30 天的临时许可证。

Markdown 是一种轻量级的标记语言,以其简洁、易读和清晰的语法而受到程序员和技术文档撰写者的喜爱。有时候,我们需要将 Markdown 文档转换为具备丰富格式和布局控制功能的 Word 文档或者适合打印和查看的PDF文件。本文将演示如何使用 Spire. Doc for .NET 和 C# 将 Markdown 文档转换为 Word 和 PDF 格式,以满足不同场景中的文档处理需求。

安装 Spire.Doc for .NET

首先,您需要将 Spire.Doc for.NET 包含的 DLL 文件作为引用添加到您的 .NET 项目中。DLL 文件可以从此链接下载,也可以通过 NuGet 安装。

PM> Install-Package Spire.Doc

C# 将 Markdown 转换为 Word

要将 Markdown 文档转换为 Word 格式,只需使用 Document.LoadFromFile(string fileName, FileFormat.Markdown) 方法加载 Markdown 文件,然后使用 Document.SaveToFile(string fileName, FileFormat.Docx) 方法将其保存为 Word 格式。

由于 Markdown 文件中的图像被存储为链接,直接将 Markdown 文件转换为 Word 文档适用于不包含图像的 Markdown 文件。如果文件包含图像,则需要在转换后进一步处理图像。

以下是将 Markdown 文件转换为 Word 文档的步骤:

  • C#
using Spire.Doc;

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

            // 加载Markdown文件
            doc.LoadFromFile("示例.md", FileFormat.Markdown);

            // 将Markdown文件转换为Word文档
            doc.SaveToFile("Markdown转Word.docx", FileFormat.Docx);
            doc.Close();
        }
    }
}

C# 将 Markdown 转换为 PDF

我们还可以直接使用 FileFormat.PDF 枚举作为参数将 Markdown 文件转换为 PDF 文件。以下是将 Markdown 文件转换为 PDF 文件的步骤:

  • C#
using Spire.Doc;

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

            // 加载Markdown文件
            doc.LoadFromFile("示例.md", FileFormat.Markdown);

            // 将Markdown文件转换为PDF文件
            doc.SaveToFile("Markdown转PDF.pdf", FileFormat.PDF);
            doc.Close();
        }
    }
}

申请临时 License

如果您希望删除结果文档中的评估消息,或者摆脱功能限制,请该Email地址已收到反垃圾邮件插件保护。要显示它您需要在浏览器中启用JavaScript。获取有效期 30 天的临时许可证。

Spire.Presentation for Java 9.4.5 已发布。本次更新修复了多线程下转换大量的文档,线程池内的任务结束后,CPU 占用达到百分之百并内存溢出的问题。详情请阅读以下内容。

问题修复:


获取 Spire.Presentation for Java 9.4.5 请点击:

https://www.e-iceblue.cn/Downloads/Spire-Presentation-JAVA.htm

Microsoft Excel 中的自动调整功能是一项方便的工具。它能够自动调整工作表中的行高度和列宽度,以适应内容的大小。当你在单元格中输入文本或数据时,内容的长度可能会超出单元格的可见范围。自动调整功能可以帮助您自动调整行高度和列宽度,确保文本或数据完全可见,而无需手动更改行高或列宽。这对于频繁更新或编辑大量数据的工作表尤其有用。在本文中,我们将介绍如何使用 Python 和 Spire.XLS for Python 在 Excel 中自动调整行高和列宽。

安装 Spire.XLS for Python

本方案需要 Spire.XLS for Python 和 plum-dispatch v1.7.4。您可以通过以下 pip 命令将它轻松安装到 Windows 中。

pip install Spire.XLS

如果您不清楚如何安装,请参考此教程: 如何在 Windows 中安装 Spire.XLS for Python

Python 在 Excel 中自动调整单行的行高和单列的列宽

要在 Excel 工作表中自动调整特定行的行高和特定列的列宽,可以使用 Worksheet.AutoFitRow() 和 Worksheet.AutoFitColumn() 方法。详细步骤如下:

  • Python
from spire.xls import *
from spire.xls.common import *

# 创建Workbook类的对象
workbook = Workbook()
# 加载Excel文件
workbook.LoadFromFile("输入.xlsx")

# 获取第一个工作表
sheet = workbook.Worksheets[0]

# 自动调整工作表中第5行的行高
sheet.AutoFitRow(5)
# 自动调整工作表中第3列的列宽
sheet.AutoFitColumn(3)

# 保存结果文件
workbook.SaveToFile("自适应特定行列.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Python 在 Excel 中自动调整行高和列宽

Python 在 Excel 中自动调整多行的行高和多列的列宽

要调整一个特定的单元格范围内的多行的行高和多列的列宽,可以使用 CellRange.AutoFitRows() 和 CellRange.AutoFitColumns() 方法。详细步骤如下:

  • Python
from spire.xls import *
from spire.xls.common import *

# 创建Workbook类的对象
workbook = Workbook()
# 加载Excel文件
workbook.LoadFromFile("输入.xlsx")

# 获取第一个工作表
sheet = workbook.Worksheets[0]

# 获取工作表中的特定单元格范围
range = sheet.Range["A1:E14"]
# 或者获取工作表中已使用的单元格范围
# range = sheet.AllocatedRange

# 自动调整单元格范围内所有行的行高
range.AutoFitRows()
# 自动调整单元格范围内所有列的列宽
range.AutoFitColumns()

# 保存结果文件
workbook.SaveToFile("自适应多个行列.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

申请临时 License

如果您希望删除结果文档中的评估消息,或者摆脱功能限制,请该Email地址已收到反垃圾邮件插件保护。要显示它您需要在浏览器中启用JavaScript。获取有效期 30 天的临时许可证。

Spire.XLS for Java 14.4.1 现已发布。该版本成功修复了转换 Excel 文档到 OFD 文档时程序抛异常的问题。见下文。

问题修复:


获取 Spire.XLS for Java 14.4.1,请点击:

https://www.e-iceblue.cn/Downloads/Spire-XLS-JAVA.html

透视表是 Excel 中强大的数据分析工具,它提供了一种灵活的方式来组织、操作和汇总数据,使用户能在不同角度上查看和比较数据,深入研究数据之间的关系和模式。通过透视表,您可以根据不同的标准(如类别、日期或数值)轻松重新排列和汇总数据。当处理复杂数据集时,您可以将不同的数据集放置在透视表中进行比较以便快速地分析并找出差异和优劣势。因此,透视表这个功能在各领域和行业都有广泛的应用。本文将介绍如何使用 Spire.XLS for Python 在 Excel 文档中创建或操作透视表。

安装 Spire.XLS for Python

本教程需要 Spire.XLS for Python 和 plum-dispatch v1.7.4。您可以通过以下 pip 命令将它们轻松安装到 Windows 中。

pip install Spire.XLS

如果您不确定如何安装,请参考此教程: 如何在 Windows 中安装 Spire.XLS for Python

Python 在 Excel 中创建透视表

要在 Excel 中创建透视表,请按照以下步骤操作:

  • Python
from spire.xls import *
from spire.xls.common import *

# 创建一个Workbook对象
workbook = Workbook()

# 加载原Excel文档
workbook.LoadFromFile("Data.xlsx")

# 获取第一个工作表
sheet = workbook.Worksheets[0]

# 指定透视表的数据范围
cellRange = sheet.Range["A1:C15"]

# 添加CellRange到PivotCaches
piVotCache = workbook.PivotCaches.Add(cellRange)

# 通过PivotCaches添加透视表并设置位置
pivotTable = sheet.PivotTables.Add("Pivot Table", sheet.Range["E1"], piVotCache)

# 设置透视表的行字段
regionField = pivotTable.PivotFields["Continent"]
regionField.Axis = AxisTypes.Row
pivotTable.Options.RowHeaderCaption = "Continent"
productField = pivotTable.PivotFields["Country"]
productField.Axis = AxisTypes.Row

# 添加值字段
pivotTable.DataFields.Add(pivotTable.PivotFields["Population"], "SUM of Population", SubtotalTypes.Sum)

# 设置透视表的样式
pivotTable.BuiltInStyle = PivotBuiltInStyles.PivotStyleMedium11

# 设置透视表相应列的列宽
h = sheet.Range["E1"]
sheet.SetColumnWidth(h.Column, 18)
sheet.SetColumnWidth(h.Column+1, 20)

# 保存文件
workbook.SaveToFile("结果.xlsx", ExcelVersion.Version2016)

# 释放对象
workbook.Dispose()

Python 在 Excel 中创建或操作数据透视表

Python 按列值对透视表进行排序

在 Python 中,可以通过列值对透视表进行排序。 首先,通过 PivotTable.PivotFields["FieldName"] 属性访问特定字段,然后使用 PivotField.SortType 属性设置其排序类型。以下是按照特定字段的值对透视表进行排序的步骤:

  • Python
from spire.xls import *
from spire.xls.common import *

# 创建一个Workbook对象
workbook = Workbook()

# 加载含有透视表的原Excel文档
workbook.LoadFromFile("透视表.xlsx")

# 获取第一个工作表
sheet = workbook.Worksheets[0]

# 获取第一个透视表
pivotTable = sheet.PivotTables[0]

# 获取要排序的字段
idField = pivotTable.PivotFields["Continent"]

# 按升序排列
idField.SortType = PivotFieldSortType.Ascending

# 保存文件
workbook.SaveToFile("结果.xlsx", ExcelVersion.Version2016)

# 释放对象
workbook.Dispose()

Python 在 Excel 中创建或操作数据透视表

Python 展开或折叠透视表中的行

在 Python 中展开或折叠数据透视表中的行,使用 PivotField.HideItemDetail(string itemValue, bool isHiddenDetail) 方法,将第二个参数设置为 true,为折叠效果;设置为 false,为展开效果。详细步骤如下:

  • Python
from spire.xls import *
from spire.xls.common import *

# 创建一个Workbook对象
workbook = Workbook()

# 加载含有透视表的原Excel文档
workbook.LoadFromFile("透视表.xlsx")

# 获取第一个工作表
sheet = workbook.Worksheets[0]

# 获取第一个透视表
pivotTable = sheet.PivotTables[0]

# 获取特定字段
idField = pivotTable.PivotFields["Continent"]

# 设置展开或折叠
idField.HideItemDetail("South America", True)
idField.HideItemDetail("North America", False)

# 保存文件
workbook.SaveToFile("结果.xlsx", ExcelVersion.Version2016)

# 释放对象
workbook.Dispose()

Python 在 Excel 中创建或操作数据透视表

申请临时 License

如果您希望删除结果文档中的评估消息,或者摆脱功能限制,请该Email地址已收到反垃圾邮件插件保护。要显示它您需要在浏览器中启用JavaScript。获取有效期 30 天的临时许可证。

Spire.PDF 10.4.2 已发布。本次更新增强了 PDF 到 OFD 以及 OFD 到 PDF 的转换功能。此外,一些已知问题也在该版本中成功修复,如不能对垂直对齐格式的文本进行高亮的问题。详情请阅读以下内容。

问题修复:


获取 Spire.PDF 10.4.2,请点击:

https://www.e-iceblue.cn/Downloads/Spire-PDF-NET.html

在 Word 文档中,内容控件使得文档的内容可以动态地更新和修改,为用户提供了更灵活的编辑和管理选项。通过内容控件,用户可以轻松地插入、删除或修改特定部分的内容,而无需改变文档的整体结构。本文将介绍如何使用 Spire.Doc for .NET 在 C# 项目中修改 Word 文档中的内容控件。

安装 Spire.Doc for .NET

首先,您需要将 Spire.Doc for .NET 包含的 DLL 文件作为引用添加到您的 .NET项目中。DLL 文件可以从此链接下载,也可以通过 NuGet 安装。

PM> Install-Package Spire.Doc

C# 修改正文内容控件

在 Spire.Doc 中,正文内容控件的对象类型是 StructureDocumentTag。您可以通过遍历 Section.Body 中的子对象集合,查找到类型为 StructureDocumentTag 的对象,然后对其进行修改。以下是详细的步骤:

  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using System.Collections.Generic;

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

            // 从文件加载文档内容
            doc.LoadFromFile("示例1.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 = "成都冰蓝科技有限公司致力于为开发人员提供 .NET 和 JAVA 组件开发产品。";

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

            // 将修改后的文档保存到文件
            doc.SaveToFile("修改Word文档正文内容控件.docx", FileFormat.Docx2016);

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

C# 修改 Word 文档中的内容控件

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

在 Spire.Doc 中,段落中的内容控件对象类型是 StructureDocumentTagInline。需要遍历 Paragraph.ChildObjects 的子对象集合,查找到类型为 StructureDocumentTagInline 的对象,然后对其进行修改。以下是详细的步骤:

  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Collections.Generic;

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

            // 从文件加载文档内容
            doc.LoadFromFile("示例2.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")
                    {
                        // 遍历StructureDocumentTagInline对象里的子对象
                        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 = "Word97-2003、Word2007、Word2010、Word2013、Word2016以及Word2019";
                            }
                        }
                    }

                    // 检查文档标记的Tag或Alias属性是否为"logo1"
                    if (structureDocumentTagInline.SDTProperties.Tag == "logo1" || structureDocumentTagInline.SDTProperties.Alias == "logo1")
                    {
                        // 遍历StructureDocumentTagInline对象里的子对象
                        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("https://cdn.e-iceblue.cn/Doc-NET.png");

                                // 设置图片宽度和高度
                                docPicture.Width = 100;
                                docPicture.Height = 100;
                            }
                        }
                    }
                }
            }
            // 将修改后的文档保存为新的文件
            doc.SaveToFile("修改Word文档的段落中的内容控件.docx", FileFormat.Docx2016);

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

C# 修改 Word 文档中的内容控件

C# 修改表格行内容控件

在 Spire.Doc 中,表格行内容控件对象类型是 StructureDocumentTagRow。需要遍历 Table.ChildObjects 的子对象集合,查找到类型为 StructureDocumentTagRow 的对象,然后对其进行修改。以下是详细的步骤:

  • C#
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("示例3.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];

                    // 检查StructureDocumentTagRow的Tag或Alias属性是否为"row1"
                    if (structureDocumentTagRow.SDTProperties.Tag == "row1" || structureDocumentTagRow.SDTProperties.Alias == "row1")
                    {
                        // 清空单元格中的段落
                        structureDocumentTagRow.Cells[0].Paragraphs.Clear();

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

            // 将修改后的文档保存到文件
            doc.SaveToFile("修改表格行内容控件.docx", FileFormat.Docx2016);

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

C# 修改 Word 文档中的内容控件

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

在 Spire.Doc 中,表格单元格内容控件对象类型是 StructureDocumentTagCell。需要遍历 TableRow.ChildObjects 的子对象集合,查找到类型为 StructureDocumentTagCell 的对象,然后对其进行操作。以下是详细的步骤:

  • C#
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("示例4.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];

                        // 检查structureDocumentTagCell的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("修改表格单元格内容控件.docx", FileFormat.Docx2016);

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

C# 修改 Word 文档中的内容控件

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

这个案例展示的是修改在表格单元格的段落中的内容控件。需要先进入单元格中的段落集合 TableCell.Pagragraphs,然后遍历每一个段落对象的子对象集合 Paragraph.ChildObjects,查找到类型为 StructureDocumentTagInline 的对象,然后对其进行修改。以下是详细的步骤:

  • C#
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("示例5.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];

                                // 检查StructureDocumentTagInline的Tag或Alias属性是否为"test1"
                                if (structureDocumentTagInline.SDTProperties.Tag == "test1" || structureDocumentTagInline.SDTProperties.Alias == "test1")
                                {
                                    // 遍历StructureDocumentTagInline的子对象
                                    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("修改表格单元格中的内容控件.docx", FileFormat.Docx2016);

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

C# 修改 Word 文档中的内容控件

申请临时 License

如果您希望删除结果文档中的评估消息,或者摆脱功能限制,请该Email地址已收到反垃圾邮件插件保护。要显示它您需要在浏览器中启用JavaScript。获取有效期 30 天的临时许可证。

PDF 文件通常包含书签,它们是可点击的链接,能方便用户浏览长文档。提取这些书签有助于创建文档大纲、分析文档结构或识别关键主题或章节。本文将介绍如何使用 Spire.PDF for Python 通过 Python 提取 PDF 文件中的书签。

安装 Spire.PDF for Python

本教程需要用到 Spire.PDF for Python 和 plum-dispatch v1.7.4。可以通过以下 pip 命令将它们轻松安装到 Windows 中。

pip install Spire.PDF

如果您不清楚如何安装,请参考: 如何在 Windows 中安装 Spire.PDF for Python

Python 提取 PDF 书签

使用 Spire.PDF for Python,您可以创建自定义方法 GetBookmarks() 和 GetChildBookmark() 来获取 PDF 文件中父书签和子书签的标题及其文本样式,然后将获取到的书签导出为 TXT 文件。具体步骤如下:

  • Python
from spire.pdf.common import *
from spire.pdf import *

inputFile = "书签.pdf"
result = "获取PDF书签.txt"

def GetChildBookmark(parentBookmark, content):
    if parentBookmark.Count > 0:
        # 遍历父书签中的每个子书签
        for i in range(parentBookmark.Count):
            childBookmark = parentBookmark.get_Item(i)
            # 获取标题
            content.append(childBookmark.Title)
            # 获取文本样式
            textStyle = str(childBookmark.DisplayStyle)
            content.append(textStyle)
            cldBk = PdfBookmarkCollection(childBookmark)
            GetChildBookmark(cldBk, content)
        
def GetBookmarks(bookmarks, result):
    # 创建StringBuilder对象
    content = []
    # 获取PDF书签信息
    if bookmarks.Count > 0:
        content.append("Pdf bookmarks:")
        # 遍历每个父书签
        for i in range(bookmarks.Count):
            parentBookmark = bookmarks.get_Item(i)
            # 获取标题
            content.append(parentBookmark.Title)
            # 获取文本样式
            textStyle = str(parentBookmark.DisplayStyle)
            content.append(textStyle)
            cldBk = PdfBookmarkCollection(parentBookmark)
            GetChildBookmark(cldBk, content)

    # 保存为txt文件
    with open(result, "w") as file:
        file.write("\n".join(content))

# 创建PdfDocument对象
pdf = PdfDocument()

# 加载PDF文件
pdf.LoadFromFile(inputFile)

# 获取PDF文件的书签集合
bookmarks = pdf.Bookmarks

# 获取书签内容并导出为TXT文件
GetBookmarks(bookmarks, result)
pdf.Close()

Python 提取 PDF 书签

申请临时 License

如果您希望删除结果文档中的评估消息,或者摆脱功能限制,请该Email地址已收到反垃圾邮件插件保护。要显示它您需要在浏览器中启用JavaScript。获取有效期 30 天的临时许可证。

在新建的 Word 文档中创建目录是提升文档质量、提高阅读体验和传达信息效果的重要手段。目录作为文档的导航指南,为读者提供了快速定位和浏览文档内容的途径。通过目录,读者可以快速了解文档的结构和内容组织,节省阅读时间,提高工作效率。目录的存在使得文档更具可读性和易用性,帮助读者快速找到感兴趣的章节或主题,减少阅读障碍。此外,目录也有助于文档的索引和检索,使得信息的查找更为便捷。本文将介绍如何使用 Spire.Doc for .NET 在 C# 项目中给新建的 Word 文档创建目录。

安装 Spire.Doc for .NET

首先,您需要将 Spire.Doc for.NET 包含的 DLL 文件作为引用添加到您的 .NET项目中。DLL 文件可以从此链接下载,也可以通过 NuGet 安装。

PM> Install-Package Spire.Doc

C# 利用标题样式创建目录

利用标题样式创建目录是一种在 Word 文档中默认自动生成目录的方法,通过使用不同级别的标题样式来标识文档中的章节和子章节,然后利用 Word 的目录功能自动生成目录内容。以下是详细的步骤:

  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using Spire.Doc.Formatting;

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

            // 在文档中添加一个节
            Section section = doc.AddSection();

            // 添加目录段落
            Paragraph TOCparagraph = section.AddParagraph();
            TOCparagraph.AppendTOC(1, 3);

            // 创建字符格式对象并设置字体
            CharacterFormat characterFormat1 = new CharacterFormat(doc);
            characterFormat1.FontName = "微软雅黑";

            // 创建另一个字符格式对象并设置字体、字体大小
            CharacterFormat characterFormat2 = new CharacterFormat(doc);
            characterFormat2.FontName = "微软雅黑";
            characterFormat2.FontSize = 12;

            // 添加标题1样式的段落
            Paragraph paragraph = section.Body.AddParagraph();
            paragraph.ApplyStyle(BuiltinStyle.Heading1);

            // 添加文本并应用字符格式
            TextRange textRange1 = paragraph.AppendText("概述");
            textRange1.ApplyCharacterFormat(characterFormat1);

            // 添加普通内容
            paragraph = section.Body.AddParagraph();
            TextRange textRange2 = paragraph.AppendText("Spire.Doc for .NET 是一款专门对 Word 文档进行操作的 .NET 类库。这款控件的主要功能在于帮助开发人员轻松快捷高效地创建、编辑、转换、比较和打印 Microsoft Word 文档。作为一款独立的 Word .NET 控件,Spire.Doc for .NET 的运行系统(服务器端或客户端)均无需安装 Microsoft Word,但是它却可以将 Microsoft Word 文档的操作功能集成到任何开发人员的 .NET (ASP.NET、Windows Form、.NET Core、.NET 5.0、.NET 6.0、.NET 7.0、.NET Standard、Xamarin、Mono Android)应用程序中。");
            textRange2.ApplyCharacterFormat(characterFormat2);

            // 添加标题1样式的段落
            paragraph = section.Body.AddParagraph();
            paragraph.ApplyStyle(BuiltinStyle.Heading1);
            textRange1 = paragraph.AppendText("主要功能");
            textRange1.ApplyCharacterFormat(characterFormat1);

            // 添加标题2样式的段落
            paragraph = section.Body.AddParagraph();
            paragraph.ApplyStyle(BuiltinStyle.Heading2);
            textRange1 = paragraph.AppendText("仅需 Spire.Doc,无需 Microsoft Office Automation");
            textRange1.ApplyCharacterFormat(characterFormat1);

            // 添加普通内容
            paragraph = section.Body.AddParagraph();
            textRange2 = paragraph.AppendText("Spire.Doc for .NET 是一个完全独立的 .NET Word 类库,它所运行的系统无需安装 Microsoft Office。Spire.Doc for .NET 和 Microsoft Word Automation 相比,优点在于稳定性高,运行速度快和可扩展性强。");
            textRange2.ApplyCharacterFormat(characterFormat2);

            // 添加标题3样式的段落
            paragraph = section.Body.AddParagraph();
            paragraph.ApplyStyle(BuiltinStyle.Heading3);
            textRange1 = paragraph.AppendText("Word 版本");
            textRange1.ApplyCharacterFormat(characterFormat1);
            paragraph = section.Body.AddParagraph();
            textRange2 = paragraph.AppendText("Word97-03  Word2007  Word2010  Word2013  Word2016  Word2019");
            textRange2.ApplyCharacterFormat(characterFormat2);

            // 添加标题2样式的段落
            paragraph = section.Body.AddParagraph();
            paragraph.ApplyStyle(BuiltinStyle.Heading2);
            textRange1 = paragraph.AppendText("高质量的文档转换");
            textRange1.ApplyCharacterFormat(characterFormat1);

            // 添加普通内容
            paragraph = section.Body.AddParagraph();
            textRange2 = paragraph.AppendText("Spire.Doc for .NET 能帮助用户将 Word 文件保存在流中,也可以保存为 Web Response,还支持将 Word 文件与 XML、RTF、EMF、TXT、XPS、EPUB、HTML、SVG、ODT 和 Markdown 等格式文件之间的双向转换。同时,它还支持将 Word 文件转换为 PDF 文件和 OFD,HTML 文件转换为图像文件。");
            textRange2.ApplyCharacterFormat(characterFormat2);

            // 添加标题2样式的段落
            paragraph = section.Body.AddParagraph();
            paragraph.ApplyStyle(BuiltinStyle.Heading2);
            textRange1 = paragraph.AppendText("多样化的 Word 文档功能");
            textRange1.ApplyCharacterFormat(characterFormat1);

            // 添加普通内容
            paragraph = section.Body.AddParagraph();
            textRange2 = paragraph.AppendText("Spire.Doc for .NET 的一个常用功能就是动态创建一个全新的 Word 文档。并支持几乎所有的 Word 文档元素,它们主要包括页面、节、页眉、页脚、数字签名、脚注、尾注、段落、项目符号和编号、表格、文本、域、超链接、书签、注释、图片、样式、背景设置、打印功能、文档设置和文档保护。同时,也支持形状、文本框、图片、OLE 对象、公式和内容控件。");
            textRange2.ApplyCharacterFormat(characterFormat2);

            // 更新目录
            doc.UpdateTableOfContents();

            // 保存文档
            doc.SaveToFile("利用标题样式创建目录.docx", FileFormat.Docx2016);

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

C# 给新建的 Word 文档创建目录

C# 利用大纲层级样式创建目录

在 Word 文档中,利用大纲层级样式也可以创建目录。可以使用 ParagraphFormat.OutlineLevel 属性来为段落指定在大纲中的层级样式。然后,通过 TableOfContent.SetTOCLevelStyle() 方法将这些大纲层级样式应用到创建目录的规则中。以下是详细的步骤:

  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using Spire.Doc.Formatting;

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

            // 定义大纲层级1
            ParagraphStyle titleStyle1 = new ParagraphStyle(doc);
            titleStyle1.Name = "T1S";
            titleStyle1.ParagraphFormat.OutlineLevel = OutlineLevel.Level1;
            titleStyle1.CharacterFormat.Bold = true;
            titleStyle1.CharacterFormat.FontName = "微软雅黑";
            titleStyle1.CharacterFormat.FontSize = 18f;
            titleStyle1.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Left;
            doc.Styles.Add(titleStyle1);

            // 定义大纲层级2
            ParagraphStyle titleStyle2 = new ParagraphStyle(doc);
            titleStyle2.Name = "T2S";
            titleStyle2.ParagraphFormat.OutlineLevel = OutlineLevel.Level2;
            titleStyle2.CharacterFormat.Bold = true;
            titleStyle2.CharacterFormat.FontName = "微软雅黑";
            titleStyle2.CharacterFormat.FontSize = 16f;
            titleStyle2.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Left;
            doc.Styles.Add(titleStyle2);

            // 定义大纲层级3
            ParagraphStyle titleStyle3 = new ParagraphStyle(doc);
            titleStyle3.Name = "T3S";
            titleStyle3.ParagraphFormat.OutlineLevel = OutlineLevel.Level3;
            titleStyle3.CharacterFormat.Bold = true;
            titleStyle3.CharacterFormat.FontName = "微软雅黑";
            titleStyle3.CharacterFormat.FontSize = 14f;
            titleStyle3.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Left;
            doc.Styles.Add(titleStyle3);

            // 添加目录段落
            Paragraph TOCparagraph = section.AddParagraph();
            TableOfContent toc = TOCparagraph.AppendTOC(1, 3);
            toc.UseHeadingStyles = false;
            toc.UseHyperlinks = true;
            toc.UseTableEntryFields = false;
            toc.RightAlignPageNumbers = true;
            toc.SetTOCLevelStyle(1, titleStyle1.Name);
            toc.SetTOCLevelStyle(2, titleStyle2.Name);
            toc.SetTOCLevelStyle(3, titleStyle3.Name);

            // 定义字符格式
            CharacterFormat characterFormat = new CharacterFormat(doc);
            characterFormat.FontName = "微软雅黑";
            characterFormat.FontSize = 12;

            // 添加段落并应用大纲层级样式1
            Paragraph paragraph = section.Body.AddParagraph();
            paragraph.ApplyStyle(titleStyle1.Name);
            paragraph.AppendText("概述");

            // 添加段落并设置文本内容
            paragraph = section.Body.AddParagraph();
            TextRange textRange = paragraph.AppendText("Spire.Doc for .NET 是一款专门对 Word 文档进行操作的 .NET 类库。这款控件的主要功能在于帮助开发人员轻松快捷高效地创建、编辑、转换、比较和打印 Microsoft Word 文档。作为一款独立的 Word .NET 控件,Spire.Doc for .NET 的运行系统(服务器端或客户端)均无需安装 Microsoft Word,但是它却可以将 Microsoft Word 文档的操作功能集成到任何开发人员的 .NET (ASP.NET、Windows Form、.NET Core、.NET 5.0、.NET 6.0、.NET 7.0、.NET Standard、Xamarin、Mono Android)应用程序中。");
            textRange.ApplyCharacterFormat(characterFormat);

            // 添加段落并应用大纲层级样式1
            paragraph = section.Body.AddParagraph();
            paragraph.ApplyStyle(titleStyle1.Name);
            paragraph.AppendText("主要功能");

            // 添加段落并应用大纲层级样式2
            paragraph = section.Body.AddParagraph();
            paragraph.ApplyStyle(titleStyle2.Name);
            paragraph.AppendText("仅需 Spire.Doc,无需 Microsoft Office Automation");

            // 添加段落并设置文本内容
            paragraph = section.Body.AddParagraph();
            textRange = paragraph.AppendText("Spire.Doc for .NET 是一个完全独立的 .NET Word 类库,它所运行的系统无需安装 Microsoft Office。Spire.Doc for .NET 和 Microsoft Word Automation 相比,优点在于稳定性高,运行速度快和可扩展性强。");
            textRange.ApplyCharacterFormat(characterFormat);

            // 添加段落并应用大纲层级样式3
            paragraph = section.Body.AddParagraph();
            paragraph.ApplyStyle(titleStyle3.Name);
            paragraph.AppendText("Word 版本");

            // 添加段落并设置文本内容
            paragraph = section.Body.AddParagraph();
            textRange = paragraph.AppendText("Word97-03  Word2007  Word2010  Word2013  Word2016  Word2019");
            textRange.ApplyCharacterFormat(characterFormat);

            // 添加段落并应用大纲层级样式2
            paragraph = section.Body.AddParagraph();
            paragraph.ApplyStyle(titleStyle2.Name);
            paragraph.AppendText("高质量的文档转换");

            // 添加段落并设置文本内容
            paragraph = section.Body.AddParagraph();
            textRange = paragraph.AppendText("Spire.Doc for .NET 能帮助用户将 Word 文件保存在流中,也可以保存为 Web Response,还支持将 Word 文件与 XML、RTF、EMF、TXT、XPS、EPUB、HTML、SVG、ODT 和 Markdown 等格式文件之间的双向转换。同时,它还支持将 Word 文件转换为 PDF 文件和 OFD,HTML 文件转换为图像文件。");
            textRange.ApplyCharacterFormat(characterFormat);

            // 添加段落并应用大纲层级样式2
            paragraph = section.Body.AddParagraph();
            paragraph.ApplyStyle(titleStyle2.Name);
            paragraph.AppendText("多样化的 Word 文档功能");

            // 添加段落并设置文本内容
            paragraph = section.Body.AddParagraph();
            textRange = paragraph.AppendText("Spire.Doc for .NET 的一个常用功能就是动态创建一个全新的 Word 文档。并支持几乎所有的 Word 文档元素,它们主要包括页面、节、页眉、页脚、数字签名、脚注、尾注、段落、项目符号和编号、表格、文本、域、超链接、书签、注释、图片、样式、背景设置、打印功能、文档设置和文档保护。同时,也支持形状、文本框、图片、OLE 对象、公式和内容控件。");
            textRange.ApplyCharacterFormat(characterFormat);

            // 更新目录内容
            doc.UpdateTableOfContents();

            // 保存文档
            doc.SaveToFile("利用大纲层级样式创建目录.docx", FileFormat.Docx2016);

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

C# 给新建的 Word 文档创建目录

C# 利用图片标题创建目录

使用 Spire.Doc 库,您可以利用 TableOfContent tocForImage = new TableOfContent(Document, " \\h \\z \\c \"图片\"") 方法通过图片标题来创建目录。以下是详细的步骤:

  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using Spire.Doc.Formatting;

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

            // 在文档中添加一个节
            Section section = doc.AddSection();

            // 创建一个图片目录对象
            TableOfContent tocForImage = new TableOfContent(doc, " \\h \\z \\c \"图片\"");

            // 在节中添加一个段落
            Paragraph tocParagraph = section.Body.AddParagraph();

            // 将图片目录对象添加到段落中
            tocParagraph.Items.Add(tocForImage);

            // 添加字段分隔符
            tocParagraph.AppendFieldMark(FieldMarkType.FieldSeparator);

            // 添加文本内容
            tocParagraph.AppendText("TOC");

            // 添加字段结束标记
            tocParagraph.AppendFieldMark(FieldMarkType.FieldEnd);

            // 在节中添加一个空白段落
            section.Body.AddParagraph();

            // 在节中添加一个段落
            Paragraph paragraph = section.Body.AddParagraph();

            // 添加一个图片
            DocPicture docPicture = paragraph.AppendPicture("images/Doc-NET.png");
            docPicture.Width = 100;
            docPicture.Height = 100;

            // 添加图片标题段落
            Paragraph pictureCaptionParagraph = docPicture.AddCaption("图片", CaptionNumberingFormat.Number, CaptionPosition.BelowItem) as Paragraph;
            pictureCaptionParagraph.AppendText("  Spire.Doc for .NET 产品 ");
            pictureCaptionParagraph.Format.AfterSpacing = 20;

            // 继续在节中添加段落
            paragraph = section.Body.AddParagraph();
            docPicture = paragraph.AppendPicture("images/PDF-NET.png");
            docPicture.Width = 100;
            docPicture.Height = 100;
            pictureCaptionParagraph = docPicture.AddCaption("图片", CaptionNumberingFormat.Number, CaptionPosition.BelowItem) as Paragraph;
            pictureCaptionParagraph.AppendText("  Spire.PDF for .NET 产品 ");
            pictureCaptionParagraph.Format.AfterSpacing = 20;
            paragraph = section.Body.AddParagraph();
            docPicture = paragraph.AppendPicture("images/XLS-NET.png");
            docPicture.Width = 100;
            docPicture.Height = 100;
            pictureCaptionParagraph = docPicture.AddCaption("图片", CaptionNumberingFormat.Number, CaptionPosition.BelowItem) as Paragraph;
            pictureCaptionParagraph.AppendText("  Spire.XLS for .NET 产品 ");
            pictureCaptionParagraph.Format.AfterSpacing = 20;
            paragraph = section.Body.AddParagraph();
            docPicture = paragraph.AppendPicture("images/PPT-NET.png");
            docPicture.Width = 100;
            docPicture.Height = 100;
            pictureCaptionParagraph = docPicture.AddCaption("图片", CaptionNumberingFormat.Number, CaptionPosition.BelowItem) as Paragraph;
            pictureCaptionParagraph.AppendText("  Spire.Presentation for .NET 产品 ");

            // 更新目录
            doc.UpdateTableOfContents(tocForImage);

            // 将文档保存为文件
            doc.SaveToFile("利用图片标题创建目录.docx", Spire.Doc.FileFormat.Docx2016);

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

C# 给新建的 Word 文档创建目录

C# 利用表格标题创建目录

同样也可以通过 TableOfContent tocForTable = new TableOfContent(Document, " \\h \\z \\c \"表格\"") 方法利用表格标题来创建目录。以下是详细的步骤:

  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using Spire.Doc.Formatting;

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

            // 在文档中添加一个节
            Section section = doc.AddSection();

            // 创建一个表格目录对象
            TableOfContent tocForTable = new TableOfContent(doc, " \\h \\z \\c \"表格\"");

            // 在节中添加一个段落用于放置表格目录
            Paragraph tocParagraph = section.Body.AddParagraph();
            tocParagraph.Items.Add(tocForTable);
            tocParagraph.AppendFieldMark(FieldMarkType.FieldSeparator);
            tocParagraph.AppendText("TOC");
            tocParagraph.AppendFieldMark(FieldMarkType.FieldEnd);

            // 在节中添加两个空白段落
            section.Body.AddParagraph();
            section.Body.AddParagraph();

            // 在节中添加一个表格
            Table table = section.Body.AddTable(true);
            table.ResetCells(1, 3);

            // 添加一个表格的标题
            Paragraph tableCaptionParagraph = table.AddCaption("表格", CaptionNumberingFormat.Number, CaptionPosition.BelowItem) as Paragraph;
            tableCaptionParagraph.AppendText("  一行三列");
            tableCaptionParagraph.Format.AfterSpacing = 18;

            // 在节中添加一个新的表格
            table = section.Body.AddTable(true);
            table.ResetCells(3, 3);

            // 添加第二个表格的标题
            tableCaptionParagraph = table.AddCaption("表格", CaptionNumberingFormat.Number, CaptionPosition.BelowItem) as Paragraph;
            tableCaptionParagraph.AppendText("  三行三列");
            tableCaptionParagraph.Format.AfterSpacing = 18;

            // 在节中添加另一个新的表格
            table = section.Body.AddTable(true);
            table.ResetCells(5, 3);

            // 添加第三个表格的标题
            tableCaptionParagraph = table.AddCaption("表格", CaptionNumberingFormat.Number, CaptionPosition.BelowItem) as Paragraph;
            tableCaptionParagraph.AppendText("  五行三列");

            // 更新表格目录
            doc.UpdateTableOfContents(tocForTable);

            // 将文档保存为指定文件
            doc.SaveToFile("利用表格标题创建目录.docx", Spire.Doc.FileFormat.Docx2016);

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

C# 给新建的 Word 文档创建目录

申请临时 License

如果您希望删除结果文档中的评估消息,或者摆脱功能限制,请该Email地址已收到反垃圾邮件插件保护。要显示它您需要在浏览器中启用JavaScript。获取有效期 30 天的临时许可证。