处理表格中的文本

正如前面的文章中提到的,表格通常包含纯文本,尽管其他内容(例如图像甚至其他表格)可以放置在表格单元格中。

使用 DocumentBuilder 类的适当方法向表添加文本或其他内容,并在 “创建一个表” 文章中进行了描述。在本文中,我们将讨论如何处理现有表格中的文本。

替换表格中的文本

该表与 Aspose.Words 中的任何其他节点一样,可以访问 Range 对象。使用表格范围对象,您可以替换表格中的文本。

目前支持在替换时使用特殊字符的功能,因此可以用多段落文本替换现有文本。为此,您需要使用相应 Replace 方法中描述的特殊元字符。

以下代码示例演示如何替换整个表格单元格中文本字符串的所有实例:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document doc = new Document(MyDir + "Tables.docx");
Table table = (Table)doc.GetChild(NodeType.Table, 0, true);
table.Range.Replace("Carrots", "Eggs", new FindReplaceOptions(FindReplaceDirection.Forward));
table.LastRow.LastCell.Range.Replace("50", "20", new FindReplaceOptions(FindReplaceDirection.Forward));
doc.Save(ArtifactsDir + "FindAndReplace.ReplaceTextInTable.docx");
view raw replace-text.cs hosted with ❤ by GitHub

从表或单元格中提取纯文本

使用 Range 对象,您还可以在整个表范围上调用方法并将表提取为纯文本。为此,请使用 Text 属性。

以下代码示例显示如何打印表格的文本范围:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document doc = new Document(MyDir + "Tables.docx");
Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
// The range text will include control characters such as "\a" for a cell.
// You can call ToString and pass SaveFormat.Text on the desired node to find the plain text content.
Console.WriteLine("Contents of the table: ");
Console.WriteLine(table.Range.Text);
view raw extract-text.cs hosted with ❤ by GitHub

使用相同的技术仅从各个表格单元格中提取内容。

以下代码示例演示如何打印行和表元素的文本范围:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Console.WriteLine("\nContents of the row: ");
Console.WriteLine(table.Rows[1].Range.Text);
Console.WriteLine("\nContents of the cell: ");
Console.WriteLine(table.LastRow.LastCell.Range.Text);

使用替代表格文本

Microsoft Word 表具有 table titletable description,它们提供表中包含的信息的替代文本表示形式。

在 Aspose.Words 中,您还可以使用 TitleDescription 属性添加表格标题和说明。这些属性对于符合 ISO/IEC 29500 的 DOCX 文档有意义。以早于 ISO/IEC 29500 的格式保存时,这些属性将被忽略。

以下代码示例显示如何设置表的标题和描述属性:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document doc = new Document(MyDir + "Tables.docx");
Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
table.Title = "Test title";
table.Description = "Test description";
OoxmlSaveOptions options = new OoxmlSaveOptions { Compliance = OoxmlCompliance.Iso29500_2008_Strict };
doc.CompatibilityOptions.OptimizeFor(Aspose.Words.Settings.MsWordVersion.Word2016);
doc.Save(ArtifactsDir + "WorkingWithTableStylesAndFormatting.TableTitleAndDescription.docx", options);