插入字段

有几种不同的方法可以将字段插入到文档中:

在本文中,我们将更详细地了解每种方式,并分析如何使用这些选项插入某些字段。

使用DocumentBuilder将字段插入文档

在Aspose.Words中,InsertField方法用于将新字段插入到文档中。 第一个参数接受要插入的字段的完整字段代码。 第二个参数是可选的,允许手动设置字段的字段结果。 如果没有提供,则该字段会自动更新。 您可以将null或empty传递给此参数以插入具有空字段值的字段。 如果您不确定特定的字段代码语法,请先在Microsoft Word中创建字段,然后切换以查看其字段代码。

下面的代码示例演示如何使用DocumentBuilder将合并字段插入到文档中:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(InsertField.class);
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.insertField("MERGEFIELD MyFieldName \\* MERGEFORMAT");
doc.save(dataDir + "output.docx");

相同的技术用于插入嵌套在其他字段中的字段。

下面的代码示例演示如何使用DocumentBuilder插入嵌套在另一个字段中的字段:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
for (int i = 0; i < 5; i++)
builder.insertBreak(BreakType.PAGE_BREAK);
builder.moveToHeaderFooter(HeaderFooterType.FOOTER_PRIMARY);
// We want to insert a field like this:
// { IF {PAGE} <> {NUMPAGES} "See Next Page" "Last Page" }
Field field = builder.insertField("IF ");
builder.moveTo(field.getSeparator());
builder.insertField("PAGE");
builder.write(" <> ");
builder.insertField("NUMPAGES");
builder.write(" \"See Next Page\" \"Last Page\" ");
field.update();
doc.save(getArtifactsDir() + "WorkingWithFields.InsertNestedFields.docx");

在字段级别指定区域设置

语言标识符是国家或地理区域语言的标准国际数字缩写。 使用Aspose.Words,您可以使用LocaleId属性在字段级别指定区域设置,该属性获取或设置字段的区域设置ID。

下面的代码示例演示如何使用此选项:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
DocumentBuilder builder = new DocumentBuilder();
Field field = builder.insertField(FieldType.FIELD_DATE, true);
field.setLocaleId(1049);
builder.getDocument().save(getArtifactsDir() + "WorkingWithFields.SpecifylocaleAtFieldlevel.docx");

插入无类型/空字段

如果您想像Microsoft Word允许的那样插入无类型/空字段({}),则可以将InsertField方法与FieldType.FieldNone参数一起使用。 要将字段插入Word文档,您可以按"Ctrl+F9"组合键。

下面的代码示例演示如何将空字段插入到文档中:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
FieldUnknown field = (FieldUnknown) builder.insertField(FieldType.FIELD_NONE, false);
doc.save(getArtifactsDir() + "WorkingWithFields.InsertFieldNone.docx");

插入COMPARE字段

COMPARE字段比较两个值,如果比较为true,则返回数值1;如果比较为false,则返回数值0。

下面的代码示例演示如何使用DocumentBuilder添加COMPARE字段:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
FieldCompare field = (FieldCompare) builder.insertField(FieldType.FIELD_COMPARE, true);
field.setLeftExpression("3");
field.setComparisonOperator("<");
field.setRightExpression("2");
field.update();
builder.writeln();
field = (FieldCompare) builder.insertField(FieldType.FIELD_COMPARE, true);
field.setLeftExpression("5");
field.setComparisonOperator("=");
field.setRightExpression("2 + 3");
field.update();
doc.updateFields();
doc.save(getArtifactsDir() + "Field.COMPARE.docx");

插入IF字段

IF字段可用于有条件地评估参数。

下面的代码示例演示如何使用DocumentBuilder添加IF字段:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.write("Statement 1: ");
FieldIf field = (FieldIf) builder.insertField(FieldType.FIELD_IF, true);
field.setLeftExpression("0");
field.setComparisonOperator("=");
field.setRightExpression("1");
// The IF field will display a string from either its "TrueText" property,
// or its "FalseText" property, depending on the truth of the statement that we have constructed.
field.setTrueText("True");
field.setFalseText("False");
field.update();
builder.write("\nStatement 2: ");
field = (FieldIf) builder.insertField(FieldType.FIELD_IF, true);
field.setLeftExpression("5");
field.setComparisonOperator("=");
field.setRightExpression("2 + 3");
field.setTrueText("True");
field.setFalseText("False");
field.update();
doc.updateFields();
doc.save(getArtifactsDir() + "Field.IF.docx");

使用FieldBuilder将字段插入文档

在Aspose.Words中插入字段的替代方法是FieldBuilder类。 它提供了流畅的接口来指定字段开关和参数值作为文本,节点甚至嵌套字段。

下面的代码示例演示如何使用FieldBuilder将字段插入到文档中:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
Document doc = new Document();
FieldBuilder firstName = new FieldBuilder(FieldType.FIELD_MERGE_FIELD);
firstName.addArgument("firstname");
FieldBuilder lastName = new FieldBuilder(FieldType.FIELD_MERGE_FIELD);
lastName.addArgument("lastname");
FieldArgumentBuilder firstnameArgumentBuilder = new FieldArgumentBuilder();
firstnameArgumentBuilder.addText("Firstname: ");
firstnameArgumentBuilder.addField(firstName);
FieldArgumentBuilder lastnameArgumentBuilder = new FieldArgumentBuilder();
lastnameArgumentBuilder.addText("Lastname: ");
lastnameArgumentBuilder.addField(lastName);
// Prepare IF field with two nested MERGEFIELD fields: { IF "left expression" = "right expression" "Firstname: { MERGEFIELD firstname }" "Lastname: { MERGEFIELD lastname }"}
FieldBuilder fieldBuilder = new FieldBuilder(FieldType.FIELD_IF);
fieldBuilder.addArgument("left expression");
fieldBuilder.addArgument("=");
fieldBuilder.addArgument("right expression");
fieldBuilder.addArgument(firstnameArgumentBuilder);
fieldBuilder.addArgument(lastnameArgumentBuilder);
// Insert IF field in exact location
Field field = fieldBuilder.buildAndInsert(doc.getFirstSection().getBody().getFirstParagraph());
field.update();
doc.save(getArtifactsDir() + "Field.InsertFieldUsingFieldBuilder.docx");

使用DOM插入字段

您还可以使用以下方法插入各种类型的字段 Aspose.Words文档对象模型(DOM). 在本节中,我们将看几个例子。

使用DOM将合并字段插入文档

MERGEFIELD field in Word document can be represented by the FieldMergeField class. You can use FieldMergeField class to perform the following operations:

  • 指定合并字段的名称
  • 指定合并字段的格式
  • 指定合并字段的字段分隔符和字段结尾之间的文本
  • 如果合并字段不为空,则指定要在合并字段后插入的文本
  • 如果合并字段不为空,则指定要在合并字段之前插入的文本

下面的代码示例演示如何使用DOM将MERGE字段添加到文档中的段落:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Paragraph para = (Paragraph) doc.getChildNodes(NodeType.PARAGRAPH, true).get(0);
builder.moveTo(para);
// We want to insert a merge field like this:
// { " MERGEFIELD Test1 \\b Test2 \\f Test3 \\m \\v" }
FieldMergeField field = (FieldMergeField) builder.insertField(FieldType.FIELD_MERGE_FIELD, false);
// { " MERGEFIELD Test1" }
field.setFieldName("Test1");
// { " MERGEFIELD Test1 \\b Test2" }
field.setTextBefore("Test2");
// { " MERGEFIELD Test1 \\b Test2 \\f Test3 }
field.setTextAfter("Test3");
// { " MERGEFIELD Test1 \\b Test2 \\f Test3 \\m" }
field.isMapped(true);
// { " MERGEFIELD Test1 \\b Test2 \\f Test3 \\m \\v" }
field.isVerticalFormatting(true);
field.update();
doc.save(getArtifactsDir() + "WorkingWithFields.InsertMergeFieldUsingDOM.docx");

使用DOM将Mail MergeADDRESSBLOCK字段插入文档

ADDRESSBLOCK字段用于在Word文档中插入Mail Merge地址块。 Word文档中的ADDRESSBLOCK字段可以由FieldAddressBlock类表示。 您可以使用FieldAddressBlock类执行以下操作:

  • 指定是否在字段中包含国家/地区的名称
  • 指定是否按照POST*CODE所定义的收件人的国家/地区设置地址格式(Universal Postal Union2006)
  • 指定排除的国家/地区名称
  • 指定名称和地址格式
  • 指定用于格式化地址的语言ID

下面的代码示例演示如何使用DOM将Mail MergeADDRESSBLOCK字段添加到文档中的段落:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Paragraph para = (Paragraph) doc.getChildNodes(NodeType.PARAGRAPH, true).get(0);
builder.moveTo(para);
// We want to insert a mail merge address block like this:
// { ADDRESSBLOCK \\c 1 \\d \\e Test2 \\f Test3 \\l \"Test 4\" }
FieldAddressBlock field = (FieldAddressBlock) builder.insertField(FieldType.FIELD_ADDRESS_BLOCK, false);
// { ADDRESSBLOCK \\c 1" }
field.setIncludeCountryOrRegionName("1");
// { ADDRESSBLOCK \\c 1 \\d" }
field.setFormatAddressOnCountryOrRegion(true);
// { ADDRESSBLOCK \\c 1 \\d \\e Test2 }
field.setExcludedCountryOrRegionName("Test2");
// { ADDRESSBLOCK \\c 1 \\d \\e Test2 \\f Test3 }
field.setNameAndAddressFormat("Test3");
// { ADDRESSBLOCK \\c 1 \\d \\e Test2 \\f Test3 \\l \"Test 4\" }
field.setLanguageId("Test 4");
field.update();
doc.save(getArtifactsDir() + "WorkingWithFields.InsertMailMergeAddressBlockFieldUsingDOM.docx");

在不使用DocumentBuilder的情况下将ADVANCE字段插入文档

ADVANCE字段用于将一行内的后续文本向左、向右、向上或向下偏移。 Word文档中的ADVANCE字段可以由FieldAdvance类表示。 您可以使用FieldAdvance类执行以下操作:

  • 指定字段后面的文本应从页面顶部边缘垂直移动的点数
  • 指定字段后面的文本应从列、框架或文本框的左边缘水平移动的点数
  • 指定字段后面的文本应向左、向右、向上或向下移动的点数

下面的代码示例演示如何使用DOM将ADVANCE字段添加到文档中的段落:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
Document doc = new Document();
Paragraph para = (Paragraph) doc.getChildNodes(NodeType.PARAGRAPH, true).get(0);
// We want to insert an Advance field like this:
// { ADVANCE \\d 10 \\l 10 \\r -3.3 \\u 0 \\x 100 \\y 100 }
FieldAdvance field = (FieldAdvance) para.appendField(FieldType.FIELD_ADVANCE, false);
// { ADVANCE \\d 10 " }
field.setDownOffset("10");
// { ADVANCE \\d 10 \\l 10 }
field.setLeftOffset("10");
// { ADVANCE \\d 10 \\l 10 \\r -3.3 }
field.setRightOffset("-3.3");
// { ADVANCE \\d 10 \\l 10 \\r -3.3 \\u 0 }
field.setUpOffset("0");
// { ADVANCE \\d 10 \\l 10 \\r -3.3 \\u 0 \\x 100 }
field.setHorizontalPosition("100");
// { ADVANCE \\d 10 \\l 10 \\r -3.3 \\u 0 \\x 100 \\y 100 }
field.setVerticalPosition("100");
field.update();
doc.save(getArtifactsDir() + "WorkingWithFields.InsertAdvanceFieldWithOutDocumentBuilder.docx");

在不使用DocumentBuilder的情况下将ASK字段插入文档

ASK字段用于提示用户将文本分配给Word文档中的书签。 Word文档中的ASK字段可以由FieldAsk类表示。 您可以使用FieldAsk类执行以下操作:

  • 指定书签的名称
  • 指定默认用户响应(提示窗口中包含的初始值)
  • 指定是否应每个Mail Merge操作接收一次用户响应
  • 指定提示文本(提示窗口的标题)

下面的代码示例演示如何使用DOM将ASK字段添加到文档中的段落:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
Document doc = new Document();
Paragraph para = (Paragraph) doc.getChildNodes(NodeType.PARAGRAPH, true).get(0);
// We want to insert an Ask field like this:
// { ASK \"Test 1\" Test2 \\d Test3 \\o }
FieldAsk field = (FieldAsk) para.appendField(FieldType.FIELD_ASK, false);
// { ASK \"Test 1\" " }
field.setBookmarkName("Test 1");
// { ASK \"Test 1\" Test2 }
field.setPromptText("Test2");
// { ASK \"Test 1\" Test2 \\d Test3 }
field.setDefaultResponse("Test3");
// { ASK \"Test 1\" Test2 \\d Test3 \\o }
field.setPromptOnceOnMailMerge(true);
field.update();
doc.save(getArtifactsDir() + "WorkingWithFields.InsertASKFieldWithOutDocumentBuilder.docx");

在不使用DocumentBuilder的情况下将AUTHOR字段插入文档

AUTHOR字段用于从Document属性中指定文档作者的名称。 Word文档中的AUTHOR字段可以由FieldAuthor类表示。 您可以使用FieldAuthor类执行以下操作:

  • 指定文档作者的姓名

下面的代码示例演示如何使用DOM将AUTHOR字段添加到文档中的段落:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
Document doc = new Document();
Paragraph para = (Paragraph) doc.getChildNodes(NodeType.PARAGRAPH, true).get(0);
// We want to insert an AUTHOR field like this:
// { AUTHOR Test1 }
FieldAuthor field = (FieldAuthor) para.appendField(FieldType.FIELD_AUTHOR, false);
field.setAuthorName("Test1"); // { AUTHOR Test1 }
field.update();
doc.save(getArtifactsDir() + "WorkingWithFields.InsertAuthorField.docx");

在不使用DocumentBuilder的情况下将INCLUDETEXT字段插入文档

INCLUDETEXT字段插入字段代码中命名的文档中包含的文本和图形。 您可以插入整个文档或书签引用的文档的一部分。 Word文档中的此字段由INCLUDETEXT表示。 您可以使用FieldIncludeText类执行以下操作:

  • 指定包含文档的书签名称
  • 指定文档的位置

下面的代码示例演示如何使用DOM将INCLUDETEXT字段添加到文档中的段落:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
Document doc = new Document();
Paragraph para = new Paragraph(doc);
// We want to insert an INCLUDETEXT field like this:
// { INCLUDETEXT "file path" }
FieldIncludeText fieldIncludeText = (FieldIncludeText) para.appendField(FieldType.FIELD_INCLUDE_TEXT, false);
fieldIncludeText.setBookmarkName("bookmark");
fieldIncludeText.setSourceFullName(getMyDir() + "IncludeText.docx");
doc.getFirstSection().getBody().appendChild(para);
fieldIncludeText.update();
doc.save(getArtifactsDir() + "WorkingWithFields.InsertIncludeFieldWithoutDocumentBuilder.docx");

在不使用DocumentBuilder的情况下将TOA字段插入文档

TOA(Table of Authorities)字段构建并插入权限表。 TOA字段收集由TA(Table of Authorities Entry)字段标记的条目。 MicrosoftOfficeWord在References选项卡上的Table of Authorities组中单击Insert Table of Authorities时插入TOA字段。 当您查看文档中的TOA字段时,语法如下所示:

{ TOA [Switches ] }

下面的代码示例演示如何使用DOM将TOA字段添加到文档中的段落。

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
Document doc = new Document();
Paragraph para = new Paragraph(doc);
// We want to insert TA and TOA fields like this:
// { TA \c 1 \l "Value 0" }
// { TOA \c 1 }
FieldTA fieldTA = (FieldTA) para.appendField(FieldType.FIELD_TOA_ENTRY, false);
fieldTA.setEntryCategory("1");
fieldTA.setLongCitation("Value 0");
doc.getFirstSection().getBody().appendChild(para);
para = new Paragraph(doc);
FieldToa fieldToa = (FieldToa) para.appendField(FieldType.FIELD_TOA, false);
fieldToa.setEntryCategory("1");
doc.getFirstSection().getBody().appendChild(para);
fieldToa.update();
doc.save(getArtifactsDir() + "WorkingWithFields.InsertTOAFieldWithoutDocumentBuilder.docx");