# How OfficeCLI Dump and Batch Commands Enable Round-Trip Document Serialization

> Discover how OfficeCLI dump and batch commands enable lossless round-trip document serialization. Extract documents to JSON and reconstruct them with ease.

- Repository: [OfficeAI/OfficeCLI](https://github.com/iofficeai/OfficeCLI)
- Tags: deep-dive
- Published: 2026-08-01

---

**The `dump` command extracts an Office document into a JSON array of replayable batch items, and the `batch` command reconstructs the document by executing those items, creating a lossless round-trip serialization pipeline.**

OfficeCLI provides a robust mechanism for **round-trip document serialization** that converts Word, PowerPoint, and Excel files into portable JSON scripts and back again. This architecture, implemented in the iOfficeAI/OfficeCLI repository, enables version-controlled document templates, programmatic document generation, and cross-environment document replication without binary file dependencies.

## The Dump Command: Extracting Structure to JSON

The `dump` command ([`CommandBuilder.Dump.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/CommandBuilder.Dump.cs)) performs the first half of the serialization cycle by traversing an OpenXML document and emitting a structured representation of its content.

### Document Handler Factory and Emitters

The process begins with `DocumentHandlerFactory.Open`, which instantiates format-specific handlers (`WordHandler`, `PowerPointHandler`, `ExcelHandler`) to abstract the OpenXML SDK operations. The dump logic delegates to specialized emitters based on file extension:

- `WordBatchEmitter` traverses Word documents
- `PptxBatchEmitter` handles PowerPoint presentations  
- `ExcelBatchEmitter` processes Excel workbooks

Each emitter walks the requested document subtree and generates a list of `BatchItem` objects describing precise operations (insert paragraph, add slide, set cell values) needed to recreate the structure later.

### Batch Items and Metadata

Before serialization, the system injects a **meta item** as the first array element via `BatchCompat.MetaItem()`. This version tag ensures the batch processor can handle compatibility differences during replay.

Any unsupported or skipped elements are collected into `CliWarning` objects and optionally written to *stderr* for visibility, ensuring the dump process completes even when encountering edge cases.

### Serialization with System.Text.Json

The final step uses `System.Text.Json` with the source-generated `BatchJsonContext` for compact, high-performance serialization:

```csharp
var (items, warnings) = Emitters.For(ext).Emit(handler, path);
items.Insert(0, BatchCompat.MetaItem());               // version tag
var json = JsonSerializer.Serialize(items,
            BatchJsonContext.Default.ListBatchItem);
File.WriteAllText(outPath, json + "\n");

```

This produces the canonical wire format consumed by the `batch` command.

## The Batch Command: Reconstructing Documents from JSON

The `batch` command ([`CommandBuilder.Batch.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/CommandBuilder.Batch.cs)) executes the inverse operation, accepting the JSON array produced by `dump` and applying it to generate a new document.

### Input Parsing and Deserialization

The command accepts input via file path (`--input <file>`) or standard input (`--input -`), reading the JSON array and deserializing it into `List<BatchItem>` using the same `BatchJsonContext` for consistency:

```csharp
var json = File.ReadAllText(inputPath);
var items = JsonSerializer.Deserialize<List<BatchItem>>(json,
            BatchJsonContext.Default.ListBatchItem);

```

### Sequential Item Application

Each `BatchItem` is applied sequentially to a document handler obtained through `DocumentHandlerFactory.Open(targetPath, editable: true)`. The execution order mirrors the dump emitter's output, ensuring structural fidelity:

```csharp
using var handler = DocumentHandlerFactory.Open(targetPath, editable: true);
foreach (var item in items) { item.Apply(handler); }
handler.Save();

```

This guarantees that the reconstructed document matches the original's content hierarchy, formatting, and data.

### Output Generation

After processing all batch items, the handler writes the resulting document to the specified target path (`--out <file>`). The result is a functionally identical copy of the original, completing the round-trip cycle.

## Practical Round-Trip Workflows

### Basic Document Replication

```bash

# Dump a Word document to JSON batch script

officecli dump mydoc.docx -o mydoc.batch.json

# Replay to reconstruct identical document

officecli batch --input mydoc.batch.json -o rebuilt.docx

```

### Streaming Without Intermediate Files

```bash

# Pipe dump output directly into batch for real-time cloning

officecli dump mydoc.pptx | officecli batch --input - -o rebuilt.pptx

```

### Programmatic JSON Envelope Mode

```bash

# Emit wrapped JSON for API consumption

officecli dump mydoc.xlsx --json -o -

# Output: {"success":true,"data":"/tmp/tmp.json","warnings":[...]}

```

## Key Source Files and Architecture

Understanding the implementation requires examining these specific files in the iOfficeAI/OfficeCLI repository:

- **[`CommandBuilder.Dump.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/CommandBuilder.Dump.cs)** – Implements dump logic, emitter selection, and metadata injection
- **[`CommandBuilder.Batch.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/CommandBuilder.Batch.cs)** – Handles JSON parsing and sequential item execution
- **[`WordBatchEmitter.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/WordBatchEmitter.cs)**, **[`PptxBatchEmitter.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/PptxBatchEmitter.cs)**, **[`ExcelBatchEmitter.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/ExcelBatchEmitter.cs)** – Format-specific traversal and batch item generation
- **[`BatchJsonContext.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/BatchJsonContext.cs)** – Source-generated JSON serialization context for `System.Text.Json`
- **[`OutputFormatter.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/OutputFormatter.cs)** – Wraps payloads in consistent JSON envelopes when using `--json` mode

## Summary

- **Round-trip document serialization** in OfficeCLI relies on the `dump` command converting OpenXML documents to JSON batch items and the `batch` command reconstructing them.
- Format-specific emitters (`WordBatchEmitter`, `PptxBatchEmitter`, `ExcelBatchEmitter`) capture every supported element as `BatchItem` objects with version metadata.
- `DocumentHandlerFactory.Open` provides abstraction across Word, PowerPoint, and Excel handlers for consistent read/write operations.
- `BatchJsonContext` enables high-performance, source-generated serialization using `System.Text.Json`.
- The pipeline supports streaming via stdin/stdout, allowing real-time document replication without temporary files.

## Frequently Asked Questions

### What file formats support round-trip serialization in OfficeCLI?

OfficeCLI supports **.docx** (Word), **.pptx** (PowerPoint), and **.xlsx** (Excel) through dedicated handlers and emitters. The `dump` command automatically selects the appropriate emitter based on file extension, while `batch` reconstructs documents using the same handler classes that perform the serialization.

### Is the dump-to-batch transformation lossless?

The transformation is **lossless for supported elements**. The emitters capture every supported structural element and content type as `BatchItem` objects, while unsupported elements generate `CliWarning` entries rather than silent failures. The meta item preserves versioning information to ensure forward compatibility.

### Can I use the batch command to generate multiple documents from one JSON file?

Yes. Since the JSON output from `dump` is a static representation of document structure, you can execute `officecli batch --input template.batch.json -o document1.docx` repeatedly with different output paths to generate unlimited identical copies from a single batch script, making it ideal for template-based document generation workflows.

### How does OfficeCLI handle large documents during serialization?

OfficeCLI uses streaming-friendly `System.Text.Json` with source-generated contexts (`BatchJsonContext`) to minimize memory overhead. Both `dump` and `batch` support piping via stdin/stdout (`--input -`), allowing processing of large documents without loading entire JSON payloads into memory buffers, and the sequential item application ensures predictable memory usage regardless of document size.