OfficeCLI Document Serialization with `dump` and `batch` Commands: A Complete Guide
**Use the officecli dump command to export any portion of a Word, PowerPoint, or Excel document as a reproducible JSON batch script, then replay it with officecli batch to rebuild the same document with guaranteed round-trip fidelity."
The OfficeCLI toolset provides a powerful document serialization pipeline that lets you treat Office documents as version-controlled, scriptable artifacts. According to the iOfficeAI/OfficeCLI source code, the dump and batch commands work together to enable round-trip fidelity, atomic rollback, and consistent warning handling across .docx, .pptx, and .xlsx files.
How Document Serialization Works in OfficeCLI
OfficeCLI's serialization architecture separates extraction (dump) from reconstruction (batch). Each command is implemented in dedicated builder classes that coordinate with format-specific emitters and a resident server for long-running sessions.
Core Components of the Serialization Pipeline
| Component | Responsibility | Key Source File |
|---|---|---|
| CommandBuilder.Dump.cs | Builds the dump verb, validates arguments, marshals subtrees into JSON |
src/officecli/CommandBuilder.Dump.cs |
| CommandBuilder.Batch.cs | Parses JSON payloads, drives replay engine, handles error modes | src/officecli/CommandBuilder.Batch.cs |
| ResidentServer.cs | Hosts persistent process, dispatches requests, implements atomic rollback | src/officecli/ResidentServer.cs |
| BatchExecutor | Shared replay loop for resident and non-resident paths | src/officecli/Core/BatchExecutor.cs |
| BatchCompat | Normalizes legacy dumps, adds meta items, converts newline encodings | src/officecli/Core/BatchCompat.cs |
| WordBatchEmitter / PptxBatchEmitter / ExcelBatchEmitter | Walk OOXML DOM, emit raw-set commands, report non-round-trippable elements | src/officecli/Handlers/* |
The dump Command: Exporting Document State
The dump command extracts a specified subtree of an Office document and serializes it as a compact JSON array of batch commands. This enables document-as-code workflows where any structural state can be captured, versioned, and replayed.
Dump Command Implementation Details
In CommandBuilder.Dump.cs, the dump flow follows this sequence:
- Extension validation — accepts
.docx,.pptx,.xlsxonly - Resident routing —
TryResidentforwards to existing process if file is already open (lines 72-79 inResidentServer.cs) - Handler instantiation —
DocumentHandlerFactory.Opencreates read-only format handler - Subtree emission —
WordBatchEmitter,PptxBatchEmitter, orExcelBatchEmitterwalks DOM and returnsList<BatchItem>plus warnings - Meta item prepending —
BatchCompat.MetaItem()adds{"command":"meta","dumpVersion":1}for version tracking - Warning handling — emits to stderr when
--jsonor--outis used, preserving cleandump | batchpipes - JSON serialization — compact output via
JsonSerializer.Serialize
Practical Dump Examples
Export an entire Word document body to JSON:
officecli dump report.docx /body -o body.json
Stream dump output directly to batch without intermediate file:
officecli dump report.docx /body --json | officecli batch new.docx --input -
Dump with explicit format specification (currently batch is the only supported format):
officecli dump presentation.pptx /slides/slide1 --format batch -o slide1.json
The batch Command: Replaying Document Scripts
The batch command reconstructs document state by executing a JSON array of batch items. It supports multiple input sources and fine-grained control over error handling and atomicity.
Batch Command Error Handling Modes
| Flag | Behavior | Source Location |
|---|---|---|
| (default) | Continue-on-error: execute all items, collect failures | CommandBuilder.Batch.cs, lines 64-70 |
--stop-on-error |
Atomic: abort on first failure, trigger rollback if resident | Lines 38-40 in ResidentServer.cs |
--best-effort |
Legacy mode: apply what succeeds, no rollback | Lines 74-88 in CommandBuilder.Batch.cs |
Batch Command Implementation Details
In CommandBuilder.Batch.cs, the batch flow handles:
- Input source detection — warns when both
--commandsand stdin are supplied (conflicting sources raise errors at lines 74-88) - Inline help —
BatchHelpDescriptiondocuments JSON shape directly in CLI - Resident dispatch — routes to
ResidentServer.ExecuteBatchfor active sessions
The ResidentServer.ExecuteBatch method (lines 38-58) implements atomic rollback:
- Flush pre-batch state to disk
- Apply batch in-memory
- On any failure, discard poisoned DOM and reload from saved state
- Restore pending whole-part payloads
- Set
_lastBatchHadFailurefor exit code propagation
Practical Batch Examples
Atomic batch with automatic rollback:
officecli batch report.docx --input body.json --stop-on-error
Best-effort application with partial success:
officecli batch report.docx --input body.json --best-effort
Inline commands without file:
officecli batch template.docx --commands '[{"command":"meta","dumpVersion":1},{"command":"raw-set","path":"/body/p[1]","value":"Updated"}]'
Batch File Format and Structure
The JSON batch format is an ordered array of BatchItem objects. The BatchCompat class in src/officecli/Core/BatchCompat.cs ensures forward and backward compatibility.
Example Batch File Structure
[
{ "command": "meta", "dumpVersion": 1 },
{ "command": "raw-set", "path": "/body/p[1]/r[1]", "value": "Hello World" },
{ "command": "raw-set", "path": "/body/p[2]/r[1]", "value": "Second paragraph" },
{ "command": "raw-set", "path": "/body/p[2]/r[1]/rPr/b", "value": "1" }
]
Compatibility Features
- Meta item: Required first element; declares
dumpVersionfor newline handling decisions - Newline encoding: Legacy
\nrewritten to\v(vertical tab) to avoid JSON serialization issues - Warning accumulation: Non-fatal issues (unrecognized LaTeX, unsupported elements) collected per-item
Format-Specific Emitters
Each Office format has dedicated emitter logic in src/officecli/Handlers/:
WordBatchEmitter.cs
- Walks WordprocessingML DOM
- Emits
raw-setfor text runs, paragraph properties, and styles - Reports custom XML parts and OLE objects as warnings (non-round-trippable)
PowerPointBatchEmitter.cs
- Handles SlideML and DrawingML subtrees
- Emits shape modifications, text frame updates, and slide layout changes
- Tracks embedded media and legacy VML shapes for warning output
ExcelBatchEmitter.cs
- Processes SpreadsheetML worksheets, shared strings, and styles
- Emits cell value sets, formula updates, and formatting commands
- Reports external links and pivot cache elements as warnings
All emitters return both the List<BatchItem> and List<CliWarning> to the dump orchestrator in CommandBuilder.Dump.cs.
Using the Resident Server for Document Serialization
The resident server eliminates file lock contention and enables true atomic transactions. When a document is opened in resident mode, subsequent dump and batch commands operate on the in-memory DOM.
Resident Flow for Dump
# Start resident (document stays open in background)
officecli resident start report.docx
# Multiple dumps without reopening
officecli dump report.docx /body -o body.json
officecli dump report.docx /tables/tbl1 -o table.json
Resident Flow for Atomic Batch
officecli resident start report.docx
# This batch is atomic: any failure triggers full rollback
officecli batch report.docx --input body.json --stop-on-error
# Exit code reflects batch success/failure
echo $?
In ResidentServer.cs (lines 12-38), rollback is implemented by:
- Saving current DOM state to temporary file
- Executing batch items via
ApplyBatchItems - On failure: disposing corrupted DOM, reloading from temp file, restoring payloads
Pipeline Patterns and Best Practices
Version Control Integration
# Extract document structure for git tracking
officecli dump spec.docx / -o spec-structure.json
git add spec-structure.json
# Later: reconstruct for review
officecli batch spec.docx --input spec-structure.json
CI/CD Document Generation
# Template + data = rendered document (non-resident, best-effort)
officecli dump template.docx / -o template.json
cat template.json | sed 's/{{VERSION}}/'"$VERSION"'/g' | \
officecli batch output.docx --input -
Cross-Format Migration
# Extract content from Word
officecli dump source.docx /body -o content.json
# Transform JSON (custom script)
python transform_json.py content.json > excel-items.json
# Apply to Excel (structure-aware adapter required)
officecli batch target.xlsx --input excel-items.json --best-effort
Summary
- The
dumpcommand extracts any document subtree as a reproducible JSON batch script, with warnings routed to stderr to preserve pipe cleanliness - The
batchcommand replays batch items with three error modes: default continue-on-error, strict--stop-on-errorwith atomic rollback, and legacy--best-effort - Atomic rollback in resident mode guarantees document integrity: pre-batch state is preserved, failures trigger DOM reload from disk
- Format-specific emitters in
WordBatchEmitter.cs,PowerPointBatchEmitter.cs, andExcelBatchEmitter.cshandle OOXML DOM walking and warn about non-round-trippable elements - Pipeline compatibility is designed into warning handling:
dump --json | batch --input -works reliably because warnings bypass stdout
Frequently Asked Questions
What file formats does OfficeCLI document serialization support?
OfficeCLI supports Word (.docx), PowerPoint (.pptx), and Excel (.xlsx) files. The dump command validates extensions in CommandBuilder.Dump.cs and routes to the appropriate emitter. Other Office formats like .doc, .ppt, and .xls (binary formats) are not supported.
Why does dump output go to stdout but warnings go to stderr?
This design enables reliable shell pipelines. When you run officecli dump ... --json | officecli batch ... --input -, the JSON stream must be clean. Warnings are diverted to stderr (triggered by --json flag or --out to file) so they don't corrupt the piped data. See lines 85-99 in CommandBuilder.Dump.cs for the warnToStderr logic.
How does atomic rollback work in resident mode?
When --stop-on-error is used with a resident server, ResidentServer.ExecuteBatch (lines 38-58) saves the pre-batch DOM to a temporary file, executes all items in memory, and monitors for failures. If any item fails, it disposes the corrupted in-memory document, reloads from the temporary file, and restores any pending whole-part payloads—leaving the original document completely unchanged.
Can I edit a batch JSON file manually?
Yes. The format is intentionally human-readable: each raw-set command specifies a DOM path and value. However, be aware that BatchCompat.PrepareForReplay in ResidentServer.cs validates and normalizes the input. Invalid paths will generate errors during replay, and --best-effort mode will skip them rather than fail.
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 →