How the merge Command in OfficeCLI Facilitates Template Merging with JSON Data

The OfficeCLI merge command replaces placeholder tokens in Word, Excel, or PowerPoint templates with values from a JSON file, using a recursive deep-merge algorithm to handle nested data and outputting the result to a specified file or stdout.

The iOfficeAI/OfficeCLI repository provides a cross-platform command-line tool for automating Office document workflows. The merge command serves as the core templating feature, enabling developers to populate document templates with structured JSON data through a sophisticated processing pipeline that handles everything from token extraction to XML manipulation.

Architecture of the OfficeCLI merge Command

The merge command is implemented across several specialized classes that form a cohesive processing pipeline. According to the source code in the iOfficeAI/OfficeCLI repository, the workflow spans from command-line parsing to final document generation.

Command Registration and CLI Options

The command definition resides in src/officecli/CommandBuilder.Merge.cs within the BuildMergeCommand method. This partial class configures the command-line interface using the following options:

  • --template (or -t): Specifies the input Office document containing placeholder tokens
  • --json (or -j): Provides the JSON data file (or - for stdin)
  • --output (or -o): Defines the output path (omitting this writes binary data to stdout)

The implementation registers these options and wires them to the processing pipeline, allowing the command to accept files in .docx, .xlsx, or .pptx formats.

Template Processing and Token Extraction

The TemplateProcessor class in src/officecli/TemplateProcessor.cs handles the initial document parsing. It opens the Office package structure and locates placeholder tokens formatted as {{tokenName}} within the document's XML parts. This class identifies the specific XML nodes that require modification—such as w:t nodes for Word documents, c:v nodes for Excel spreadsheets, and p:txBody nodes for PowerPoint presentations.

Deep-Merge Algorithm for Nested JSON Data

When processing complex data structures, the merge command utilizes the DeepMerge class located in src/officecli/DeepMerge.cs. This implementation recursively walks both the template's token hierarchy and the JSON object tree, applying a "last-one-wins" strategy for duplicate keys.

The MergeJson method combines base and overlay JSON objects:

public static JsonObject MergeJson(JsonObject baseObj, JsonObject overlay)
{
    var merged = new JsonObject();
    foreach (var kv in baseObj) merged[kv.Key] = kv.Value?.DeepClone();
    foreach (var kv in overlay)
    {
        if (merged.ContainsKey(kv.Key) && kv.Value is JsonObject subOverlay &&
            merged[kv.Key] is JsonObject subBase)
            merged[kv.Key] = MergeJson(subBase, subOverlay);
        else
            merged[kv.Key] = kv.Value?.DeepClone();
    }
    return merged;
}

This recursive approach ensures that nested objects in your JSON payload properly populate hierarchical template structures without flattening the data prematurely.

Token Replacement and Document Generation

The final step in the pipeline occurs in src/officecli/TemplateRewriter.cs. The ReplaceTokens method iterates through discovered tokens and substitutes them with values from the merged JSON dictionary:

foreach (var token in tokens)
{
    if (data.TryGetValue(token.Name, out var value))
        token.XmlNode.InnerText = value.ToString();
}

After substitution, the modified Office package is saved to the output path specified via --output. If the output flag is omitted, the CLI writes the resulting document to stdout in binary form, enabling Unix-style piping in shell scripts.

Practical Usage Examples

The following examples demonstrate how to invoke the merge command across different scenarios.

Basic Template Merging

Combine a Word template with a JSON data file:

officecli merge \
    --template template.docx \
    --json data.json \
    --output merged.docx

Piping JSON from stdin

Process data streams without intermediate files:

cat data.json | officecli merge \
    --template template.pptx \
    --json - \
    --output result.pptx

PowerShell Execution

Windows users can execute the command using PowerShell syntax:

officecli merge --template "C:\templates\report.xlsx" `
                --json "C:\data\report.json" `
                --output "C:\output\report-merged.xlsx"

Summary

  • The OfficeCLI merge command processes Word, Excel, and PowerPoint templates containing {{token}} placeholders.
  • JSON deserialization utilizes System.Text.Json with options defined in src/officecli/JsonHelpers.cs.
  • The DeepMerge.MergeJson method in src/officecli/DeepMerge.cs recursively merges nested JSON objects using a last-one-wins strategy.
  • Token replacement targets specific XML nodes (w:t, c:v, p:txBody) via the TemplateRewriter class.
  • Output can be directed to a file via --output or streamed as binary data to stdout for piping.

Frequently Asked Questions

What file formats does the OfficeCLI merge command support?

The merge command accepts Office Open XML formats including Word documents (.docx), Excel spreadsheets (.xlsx), and PowerPoint presentations (.pptx). The TemplateProcessor class parses the underlying XML structure of these packages to locate and replace placeholder tokens.

How does the merge command handle nested JSON objects?

The command implements recursive deep-merging through the DeepMerge class in src/officecli/DeepMerge.cs. When encountering nested objects, the algorithm recursively traverses both the JSON structure and template hierarchy, ensuring that deeply nested values correctly map to their corresponding tokens without flattening the data structure.

Can I output the merged document to stdout instead of a file?

Yes. If you omit the --output (or -o) flag, the merge command writes the resulting Office document to stdout in binary format. This behavior supports Unix-style piping, allowing you to chain the output to other command-line tools or redirection operations.

Where is the merge command logic implemented in the OfficeCLI source code?

The command logic is distributed across several files: src/officecli/CommandBuilder.Merge.cs defines the CLI interface and options; src/officecli/TemplateProcessor.cs handles document parsing and token extraction; src/officecli/DeepMerge.cs contains the JSON merging algorithm; and src/officecli/TemplateRewriter.cs performs the actual token substitution and XML manipulation.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →