How to Use Dump and Batch Commands for Round-Trip Document Editing with OfficeCLI
OfficeCLI's dump and batch commands enable round-trip document editing by serializing a document's DOM subtree into a JSON batch script that can be modified programmatically and replayed atomically onto the original or a new file.
OfficeCLI is an open-source command-line tool for automating Microsoft Office document manipulation. The round-trip document editing workflow uses dump to extract a document's current state as a replayable JSON array and batch to apply modifications back to the file atomically, supporting DOCX, PPTX, and XLSX formats.
Step 1: Extract Document State with dump
The dump command serializes a DOM subtree into a compact JSON batch script. Implemented in src/officecli/CommandBuilder.Dump.cs, this command validates file extensions (.docx, .pptx, .xlsx), routes through any running resident process via TryResident to avoid file locks, and emits the serialized structure to stdout or a file.
The command prepends a meta item using BatchCompat.MetaItem() that records the dump version and handles line-break normalization (\v). When --out specifies a file path rather than - (stdout), warnings write to stderr to ensure human-readable feedback is not lost.
officecli dump report.docx / --format batch -o report.json
This extracts the complete document structure into report.json, beginning with {"command":"meta","dumpVersion":1} followed by the command sequence needed to recreate that state. To extract specific subtrees, provide a path argument such as /slide[1] for PowerPoint or /body/p[2] for Word documents.
Step 2: Replay Modifications with batch
The batch command, implemented in src/officecli/CommandBuilder.Batch.cs, replays JSON batch scripts against target documents. It accepts input via three methods:
--commands(inline JSON string)--input <file>(file path)--input -(stdin)
The command automatically unwraps JSON envelopes produced by dump --json, enabling direct piping without tools like jq.
Atomic Execution and File Safety
For non-resident execution, batch creates a temporary copy at tmpPath, applies all commands via RunNonResidentBatch, and atomically promotes the result using File.Replace only upon complete success. This guarantees the original file remains untouched if any operation fails. When a resident server is running, the entire batch transmits as a single request through ResidentClient.TrySend, executing entirely in memory without temporary files.
Validation and Protection
The command performs pre-validation against BatchItem.KnownFields to reject unknown fields, null entries, or empty arrays before deserialization. For .docx files, protection checks via GetBatchProtectionBlock run once per batch, mirroring the set command behavior. Use --force to bypass these protection gates when necessary.
officecli batch document.docx --input changes.json
Error Handling and Execution Modes
OfficeCLI provides three mutually exclusive flags to control failure behavior:
--stop-on-error: Aborts immediately on the first failure (fail-fast mode for CI validation)--best-effort: Applies all successful commands while reporting failures, persisting partial changes rather than rolling back--force: Bypasses document protection checks (use with caution on protected Word documents)
Exit codes follow a strict convention: 0 for success, 1 for errors (unless --best-effort is specified), and 2 for pure warnings such as unrecognized LaTeX tokens. In --json mode, warnings populate the CliWarning array inside the JSON envelope generated by OutputFormatter.WrapEnvelope.
Practical Round-Trip Examples
Extract and Replay In-Place
Dump a complete document and apply it back to the same file atomically:
officecli dump presentation.pptx / --format batch -o backup.json
officecli batch presentation.pptx --input backup.json
If any batch item fails, the atomic replacement ensures presentation.pptx remains in its original state.
Stream Dump Directly to Batch
Pipe modifications without intermediate files:
officecli dump template.docx / --format batch --json | \
officecli batch target.docx --input -
The --json flag wraps the dump in {"data":[...]}, which batch automatically unwraps before processing via --input - (stdin).
Clean-Slate Document Generation
Create a fresh document and apply a dumped configuration:
officecli create new.pptx
officecli batch new.pptx --input template.json
As documented in BatchHelpDescription (lines 18-44 of CommandBuilder.Help.cs), follow the idiom close → rm → create → batch → close to avoid "already exists" errors when regenerating files from scratch.
Strict Validation for CI Pipelines
Abort immediately on first error for automated validation:
officecli batch critical.xlsx --input updates.json --stop-on-error
Best-Effort Migration
Apply successful commands while logging failures:
officecli batch legacy.docx --input partial.json --best-effort
Override Protected Documents
Force changes onto protected Word documents:
officecli batch protected.docx --input changes.json --force
Key Implementation Files
The round-trip functionality spans several core files:
src/officecli/CommandBuilder.Dump.cs: Implements argument parsing, handler selection (WordHandler,PowerPointHandler,ExcelHandler), warning collection to stderr, and meta-item insertion.src/officecli/CommandBuilder.Batch.cs: Handles input parsing, resident vs non-resident execution paths, atomic file replacement logic viaFile.Replace, and protection checks.src/officecli/Core/BatchCompat.cs: Provides compatibility utilities includingMetaItemgeneration and line-break normalization viaPrepareForReplay.src/officecli/BatchTypes.cs: Defines theBatchItemandBatchResultstructures used for serialization and validation againstKnownFields.
Summary
- The
dumpcommand extracts document DOM subtrees as JSON batch scripts with embedded metadata, supporting granular paths like/body/p[2]for targeted extraction. - The
batchcommand replays JSON scripts atomically, using temporary files andFile.Replacefor non-resident execution or in-memory processing via resident servers. - Three error modes—
--stop-on-error,--best-effort, and--force—provide fine-grained control over validation and failure handling with specific exit codes (1 for errors, 2 for warnings). - Direct piping via
dump --json | batch --input -enables streamlined automation without temporary files. - All handlers emit warnings to stderr and, in JSON mode, wrap output using
OutputFormatter.WrapEnvelopefor reliable API consumption.
Frequently Asked Questions
Can I extract only a specific section of a document instead of the whole file?
Yes. The dump command accepts a path argument (e.g., /slide[1] for PowerPoint or /body/p[2] for Word) that targets specific DOM subtrees. This generates a JSON batch containing only the commands necessary to recreate that section, which you can then modify and replay onto other documents.
What happens if a batch command fails midway through execution?
By default, the batch is atomic: it rolls back all changes and preserves the original file, exiting with code 1. If you specify --best-effort, successful commands persist while failures are reported via stderr. Use --stop-on-error to ensure immediate termination at the first failure, which is essential for CI/CD validation pipelines.
How does OfficeCLI handle file locking when editing documents?
Both commands route through TryResident to check for a running resident process, avoiding file-lock conflicts. For batch operations without a resident, the tool creates a temporary copy, applies changes there, and atomically replaces the original only upon success, ensuring the source file is never in a partially modified state.
Can I use dump and batch to migrate content between different Office formats?
While the batch format is standardized, the emitters (WordBatchEmitter, PptxBatchEmitter, ExcelBatchEmitter) generate format-specific commands. You can dump from one file and batch into another format only if the command types are compatible. For reliable migration, use officecli create to generate a fresh target document of the desired format, then apply the batch to populate it.
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:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →