自定义字段属性
Contents
[
Hide
]
Aspose.Words提供了以编程方式与各种字段属性交互的功能。 在本文中,我们将看几个示例,以便您了解使用字段属性的基本原理。 您可以在Fields namespace中查看相应类中每个字段类型的完整属性列表。
字段属性更新
有时用户需要更改字段属性的值。 例如,更新AUTHOR
字段的AuthorName属性或更改MERGEFIELD
字段的FieldName属性。
下面的代码示例演示如何重命名Word文档中的合并字段:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C | |
auto doc = MakeObject<Document>(); | |
auto builder = MakeObject<DocumentBuilder>(doc); | |
builder->InsertField(u"MERGEFIELD MyMergeField1 \\* MERGEFORMAT"); | |
builder->InsertField(u"MERGEFIELD MyMergeField2 \\* MERGEFORMAT"); | |
// Select all field start nodes so we can find the merge fields. | |
SharedPtr<NodeCollection> fieldStarts = doc->GetChildNodes(NodeType::FieldStart, true); | |
for (const auto& fieldStart : System::IterateOver<FieldStart>(fieldStarts)) | |
{ | |
if (fieldStart->get_FieldType() == FieldType::FieldMergeField) | |
{ | |
auto mergeField = MakeObject<WorkingWithFields::MergeField>(fieldStart); | |
mergeField->set_Name(mergeField->get_Name() + u"_Renamed"); | |
} | |
} | |
doc->Save(ArtifactsDir + u"WorkingWithFields.RenameMergeFields.docx"); |
字段显示结果
Aspose.Words为没有字段分隔符节点的字段提供属性以获取字段的结果。 我们称之为"假结果"或显示结果;Microsoft Word通过动态计算字段的值在文档中显示它,但文档模型中没有这样的值。
下面的代码示例演示DisplayResult属性的用法:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C | |
auto doc = MakeObject<Document>(MyDir + u"Various fields.docx"); | |
doc->UpdateFields(); | |
for (const auto& field : System::IterateOver(document->get_Range()->get_Fields())) | |
{ | |
std::cout << field->get_DisplayResult() << std::endl; | |
} |