使用表格中的文本

如前几篇文章所述,表格通常包含纯文本,尽管其他内容(如图像甚至其他表格)可以放置在表格单元格中。

向表中添加文本或其他内容是使用DocumentBuilder类的适当方法进行的,并在**“Create a Table”**文章中进行了描述。 在本文中,我们将讨论如何在已经存在的表中处理文本。

替换表中的文本

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

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

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

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git.
auto doc = MakeObject<Document>(MyDir + u"Tables.docx");
auto table = System::ExplicitCast<Table>(doc->GetChild(NodeType::Table, 0, true));
table->get_Range()->Replace(u"Carrots", u"Eggs", MakeObject<FindReplaceOptions>(FindReplaceDirection::Forward));
table->get_LastRow()->get_LastCell()->get_Range()->Replace(u"50", u"20", MakeObject<FindReplaceOptions>(FindReplaceDirection::Forward));
doc->Save(ArtifactsDir + u"FindAndReplace.ReplaceTextInTable.docx");
view raw replace-text.h hosted with ❤ by GitHub

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

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

下面的代码示例演示如何打印表的文本范围:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git.
auto doc = MakeObject<Document>(MyDir + u"Tables.docx");
auto table = System::ExplicitCast<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.
std::cout << "Contents of the table: " << std::endl;
std::cout << table->get_Range()->get_Text() << std::endl;
view raw extract-text.h hosted with ❤ by GitHub

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

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

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git.
std::cout << "\nContents of the row: " << std::endl;
std::cout << table->get_Rows()->idx_get(1)->get_Range()->get_Text() << std::endl;
std::cout << "\nContents of the cell: " << std::endl;
std::cout << table->get_LastRow()->get_LastCell()->get_Range()->get_Text() << std::endl;

使用替代表格文本

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

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

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

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git.
auto doc = MakeObject<Document>(MyDir + u"Tables.docx");
auto table = System::ExplicitCast<Table>(doc->GetChild(NodeType::Table, 0, true));
table->set_Title(u"Test title");
table->set_Description(u"Test description");
auto options = MakeObject<OoxmlSaveOptions>();
options->set_Compliance(OoxmlCompliance::Iso29500_2008_Strict);
doc->get_CompatibilityOptions()->OptimizeFor(Settings::MsWordVersion::Word2016);
doc->Save(ArtifactsDir + u"WorkingWithTableStylesAndFormatting.TableTitleAndDescription.docx", options);