Merge pull request #928 from pauldegroot/simple-mailmerge-fields

Added support for w:fldSimple, including convenience for MailMerge
This commit is contained in:
Dolan
2021-05-06 15:41:37 +01:00
committed by GitHub
6 changed files with 182 additions and 2 deletions

43
demo/66-fields.ts Normal file
View File

@ -0,0 +1,43 @@
// Use fields to include dynamic text
// Import from 'docx' rather than '../build' if you install from npm
import * as fs from "fs";
import { Bookmark, Document, Packer, Paragraph, SimpleField, TextRun } from "../build";
const doc = new Document({
creator: 'Me',
sections: [
{
properties: {},
children: [
new Paragraph({
children: [
new TextRun("This document is called "),
new SimpleField("FILENAME", "My Document.docx"),
new TextRun(", was created on "),
new SimpleField('CREATEDATE \\@ "d MMMM yyyy"'),
new TextRun(" by "),
new SimpleField("AUTHOR"),
],
}),
new Paragraph({
children: [
new TextRun("The document has "),
new SimpleField("NUMWORDS", "34"),
new TextRun(" words and if you'd print it "),
new Bookmark({
id: "TimesPrinted",
children: [new TextRun("42")],
}),
new TextRun(" times two-sided, you would need "),
new SimpleField("=INT((TimesPrinted+1)/2)"),
new TextRun(" sheets of paper."),
],
}),
],
},
],
});
Packer.toBuffer(doc).then((buffer) => {
fs.writeFileSync("My Document.docx", buffer);
});

73
docs/usage/fields.md Normal file
View File

@ -0,0 +1,73 @@
# Fields
Fields are pieces of dynamic text that you can include in your document. Often used fields are page numbers or references, but you can also include document properties like the author name or last saved date.
## Simple fields
There are very complicated fields like the table of contents, but in many cases the whole field just has the same properties (like formatting). In those cases, you can use simple fields.
Word uses field codes to identify what the result of the field should be. You can find these field codes by adding a field in a document (`Insert -> Quick Parts -> Field...`) and clicking the 'Field codes'-button. Some examples include:
Field type | Example | Description
----------- | --------------- | ---------------------------------------------------------
= (Formula) | `=2*21` | Calculates the result of a formula. You can also use bookmarks as variables, see below.
Author | `AUTHOR` | Includes the author mentioned in the document properties.
CreateDate | `CREATEDATE` | Date the document was created.
Date | `DATE` | Today's date.
FileName | `FILENAME \p` | The name of the document. Add `\p` for the complete path.
Info | `INFO NumWords` | Data from the document properties, e.g. the number of words in the document.
NumPages | `NUMPAGES` | Number of pages in the document.
UserName | `USERNAME` | Your user name from the Office personalization settings.
Fields can be added as a child of a paragraph:
```ts
const paragraph = new Paragraph({
children: [new TextRun("This document was created by: "), new SimpleField("AUTHOR")],
});
```
Fields can contain a cached value that gives the word processor a text to show without having to calculate all fields. The cached value can be updated by selecting the field and pressing F9. A cached value can be passed in as the second argument to the constructor.
```ts
const paragraph = new Paragraph({
children: [new TextRun("This document was created by: "), new SimpleField("AUTHOR", "Richard Brodie")],
});
```
### Formulas
One type of field is the formula that can be used to do some basic calculations. This can be done with static values, e.g. `12 + 34`, but a value from a bookmark can also be used in a calculation. This can be seen in the following example:
```ts
const paragraph = new Paragraph({
children: [
new TextRun("Value one is: "),
new Bookmark({ id: "One", children: [new TextRun("451")]}),
new TextRun(". The second value is: "),
new Bookmark({ id: "Two", children: [new TextRun("886")]}),
new TextRun(". The sum of these values is: "),
new SimpleField("=One+Two"),
],
});
```
### Mail merge fields
Fields are often used in a mail merge where a template document is created and data from another source (Excel or a database) is inserted in the document.
A convenience class was added to add these mail merge fields to the document easily. You can add these to a paragraph like any other field and only have to supply the name of the field in your data set:
```ts
const paragraph = new Paragraph({
children: [new TextRun("Your score was "), new SimpleMailMergeField("Score"), new TextRun(" of 100 points")],
});
```
This code is equivalent to:
```ts
const paragraph = new Paragraph({
children: [new TextRun("Your score was "), new SimpleField("MERGEFIELD Score", "«Score»"), new TextRun(" of 100 points")],
});
```

View File

@ -10,7 +10,7 @@ import { PageBreak } from "./formatting/page-break";
import { Bookmark, ConcreteHyperlink, ExternalHyperlink, InternalHyperlink } from "./links"; import { Bookmark, ConcreteHyperlink, ExternalHyperlink, InternalHyperlink } from "./links";
import { Math } from "./math"; import { Math } from "./math";
import { IParagraphPropertiesOptions, ParagraphProperties } from "./properties"; import { IParagraphPropertiesOptions, ParagraphProperties } from "./properties";
import { ImageRun, Run, SequentialIdentifier, SymbolRun, TextRun } from "./run"; import { ImageRun, Run, SequentialIdentifier, SimpleField, SimpleMailMergeField, SymbolRun, TextRun } from "./run";
export type ParagraphChild = export type ParagraphChild =
| TextRun | TextRun
@ -24,7 +24,9 @@ export type ParagraphChild =
| ExternalHyperlink | ExternalHyperlink
| InsertedTextRun | InsertedTextRun
| DeletedTextRun | DeletedTextRun
| Math; | Math
| SimpleField
| SimpleMailMergeField;
export interface IParagraphOptions extends IParagraphPropertiesOptions { export interface IParagraphOptions extends IParagraphPropertiesOptions {
readonly text?: string; readonly text?: string;

View File

@ -8,3 +8,4 @@ export * from "./sequential-identifier";
export * from "./underline"; export * from "./underline";
export * from "./emphasis-mark"; export * from "./emphasis-mark";
export * from "./tab"; export * from "./tab";
export * from "./simple-field";

View File

@ -0,0 +1,38 @@
import { expect } from "chai";
import { Formatter } from "export/formatter";
import { SimpleField, SimpleMailMergeField } from "./simple-field";
describe("SimpleField", () => {
describe("#constructor()", () => {
it("uses the instruction given", () => {
const tree = new Formatter().format(new SimpleField("FILENAME"));
expect(tree).to.deep.equal({ "w:fldSimple": { _attr: { "w:instr": "FILENAME" } } });
});
it("accepts a cached value", () => {
const tree = new Formatter().format(new SimpleField("FILENAME", "ExampleDoc.docx"));
expect(tree).to.deep.equal({
"w:fldSimple": [
{ _attr: { "w:instr": "FILENAME" } },
{ "w:r": [{ "w:t": [{ _attr: { "xml:space": "preserve" } }, "ExampleDoc.docx"] }] },
],
});
});
});
});
describe("SimpleMailMergeField", () => {
describe("#constructor()", () => {
it("creates a simple field", () => {
const tree = new Formatter().format(new SimpleMailMergeField("Name"));
expect(tree).to.deep.equal({
"w:fldSimple": [
{ _attr: { "w:instr": " MERGEFIELD Name " } },
{ "w:r": [{ "w:t": [{ _attr: { "xml:space": "preserve" } }, "«Name»"] }] },
],
});
});
});
});

View File

@ -0,0 +1,23 @@
// http://www.datypic.com/sc/ooxml/e-w_fldSimple-1.html
import { XmlAttributeComponent, XmlComponent } from "file/xml-components";
import { TextRun } from "./text-run";
class FldSimpleAttrs extends XmlAttributeComponent<{ readonly instr: string }> {
protected readonly xmlKeys = { instr: "w:instr" };
}
export class SimpleField extends XmlComponent {
constructor(instruction: string, cachedValue?: string) {
super("w:fldSimple");
this.root.push(new FldSimpleAttrs({ instr: instruction }));
if (cachedValue !== undefined) {
this.root.push(new TextRun(cachedValue));
}
}
}
export class SimpleMailMergeField extends SimpleField {
constructor(fieldName: string) {
super(` MERGEFIELD ${fieldName} `, `«${fieldName}»`);
}
}