How to Use OfficeCLI to Format Text in Word Documents: A Complete Guide

OfficeCLI is a self-contained binary that speaks OpenXML natively, exposing a path-based DOM for Word documents where you format text by setting properties like bold, color, and align on specific elements using the set or add commands without any Microsoft Office installation.

OfficeCLI enables direct manipulation of .docx files through a command-line interface that parses documents into an in-memory DOM and applies mutations before writing back valid OOXML. This guide demonstrates how to format text in Word documents using OfficeCLI's property-based approach, with examples drawn from the iOfficeAI/OfficeCLI repository.

Understanding the OfficeCLI Architecture

OfficeCLI operates through three distinct layers when interacting with Word documents. The Read layer provides high-level views via commands like view and get. The DOM layer handles structured element manipulation through add, set, remove, move, and query. The Raw XML layer allows direct XPath edits using raw and raw-set when precise control is required.

Because the binary embeds the .NET runtime, there is no external Office installation required. This architecture makes OfficeCLI safe for CI/CD pipelines and container environments while maintaining full compatibility with the OpenXML specification.

The Word Formatting Model

OfficeCLI recognizes three categories of formatting properties that correspond to Word's document structure:

  • Paragraph-level properties affect entire paragraphs, including align, indent, spaceBefore, and shading.fill.
  • Run-level properties target text runs within paragraphs, such as bold, italic, color, and underline.
  • Mark-run properties format the paragraph mark (pilcrow) itself using the markRPr.* namespace.

All properties accept human-friendly shorthand values. For example, color=FF0000, size=14pt, and border=single;8;FF0000 are automatically validated against the schema, with structured error objects returned when values are unsupported or out of range.

Formatting Text with CLI Commands

The CLI provides two primary approaches to apply formatting: creating new formatted elements or modifying existing ones.

Creating New Formatted Paragraphs

Use the add command with the --type paragraph flag and --prop arguments to create content with formatting applied at creation. Paths follow the DOM hierarchy such as /body for document body insertion.


# Create a fresh document

officecli create formatted.docx

# Title – centered, large, bold

officecli add formatted.docx /body \
  --type paragraph \
  --prop "text=Document Title" \
  --prop align=center \
  --prop size=24 \
  --prop bold=true

# Body paragraph – left aligned, 12pt, blue text, 1.5× line spacing

officecli add formatted.docx /body \
  --type paragraph \
  --prop "text=This is a formatted paragraph." \
  --prop align=left \
  --prop size=12pt \
  --prop color=0000FF \
  --prop lineSpacing=1.5x

# Indented block quote – first-line indent + gray shading

officecli add formatted.docx /body \
  --type paragraph \
  --prop "text=Quote: Important citation here" \
  --prop firstLineIndent=1cm \
  --prop shading.fill=D9D9D9

Modifying Existing Text Runs

Target specific elements using stable paths like /body/p[3]/r[1] (third paragraph, first run) and apply the set command to update properties without recreating the element.


# Change specific text to italic with yellow highlighting

officecli set formatted.docx '/body/p[2]/r[1]' \
  --prop italic=true \
  --prop highlight=yellow

Batch Processing with the Python SDK

For complex documents requiring multiple formatting operations, the Python SDK provides a resident session via a pipe to the binary. The officecli.create() context manager handles document lifecycle, while doc.batch() accepts an array of command dictionaries.

The following example from examples/word/paragraph-formatting.py demonstrates building a richly formatted document programmatically:

import officecli

FILE = "paragraph-formatting.docx"

def para(text, **props):
    return {"command": "add", "parent": "/body", "type": "paragraph",
            "props": {"text": text, **props}}

def heading(text):
    return para(text, bold="true", size="14", color="1F4E79", spaceBefore="10pt")

with officecli.create(FILE, "--force") as doc:
    items = [
        # Title

        para("Paragraph Formatting Showcase", align="center", bold="true", size="20"),

        # Alignment demo

        heading("Alignment"),
        para("Left aligned (default)", align="left"),
        para("Center aligned", align="center"),
        para("Right aligned", align="right"),
        para("Justified text with adjusted spacing", align="both"),

        # Indentation demo

        heading("Indentation"),
        para("Left indent 1cm", indent="1cm"),
        para("First-line indent", firstLineIndent="1cm"),

        # Run-level formatting

        heading("Run formatting"),
        para("Bold + red", bold="true", color="C00000", size="13"),
        para("Italic + highlighted", italic="true", highlight="yellow"),

        # Shading and borders

        heading("Shading & borders"),
        para("Light gray shading", **{"shading.fill": "D9D9D9"}),
        para("Box border, all sides", border="single;8;FF0000"),
    ]
    doc.batch(items)

The equivalent bash implementation lives in examples/word/paragraph-formatting.sh, demonstrating identical functionality using shell commands and --prop flags.

Summary

  • OfficeCLI manipulates Word documents through a path-based DOM where elements are addressable via stable paths like /body/p[2]/r[1].
  • Paragraph-level properties (align, indent, shading) affect entire blocks, while run-level properties (bold, italic, color) target specific text spans.
  • The add command creates formatted content, while set modifies existing elements using declarative property assignments.
  • The Python SDK (sdk/python/officecli.py) enables batch processing through the batch() method for high-throughput document generation.
  • All operations require no Microsoft Office installation, making the tool suitable for automated workflows and server environments.

Frequently Asked Questions

What is the difference between paragraph-level and run-level formatting in OfficeCLI?

Paragraph-level properties affect the entire paragraph block, including alignment, indentation, spacing, and background shading. Run-level properties target specific text segments within a paragraph, controlling attributes like bold, italic, font color, and underline. In the OfficeCLI path syntax, paragraph properties are set on /body/p[n] elements, while run properties are set on /body/p[n]/r[n] elements.

How do I target specific text elements using OfficeCLI paths?

OfficeCLI uses a stable path syntax similar to XPath where /body represents the document body, p[3] selects the third paragraph, and r[1] selects the first text run within that paragraph. These paths remain consistent across document saves, allowing reliable scripting. For precise targeting of formatting, first use officecli view formatted.docx to inspect the document structure and identify the correct path indices.

Can I use OfficeCLI in CI/CD pipelines without installing Microsoft Word?

Yes. OfficeCLI is a self-contained binary that embeds the .NET runtime and speaks OpenXML directly without any dependency on Microsoft Office or Windows. This makes it safe to run in Linux containers, GitHub Actions, and other automated environments where traditional COM automation would fail or require expensive licensing.

Where can I find the complete list of supported formatting properties?

The repository maintains a comprehensive reference at examples/word/paragraph-formatting.py and examples/word/paragraph-formatting.sh demonstrating every supported property. For detailed schema documentation, consult the wiki/word-reference page in the iOfficeAI/OfficeCLI repository, which catalogs all paragraph, run, and markRPr properties including valid value ranges and shorthand syntax.

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 →