How to Use the OfficeCLI `query` Command to Search and Filter Elements Within Documents
The OfficeCLI query command uses CSS-like selectors to search and filter elements in Word, Excel, and PowerPoint documents, with support for attribute filtering, text matching, JSON output, and compact text formats.
The query command is a read-only operation designed for probing Office documents programmatically. Whether you're automating document inspection, extracting data for reporting, or building CI/CD pipelines, this command provides a fast, script-friendly interface to enumerate and filter document elements. This article explains how the query command works according to the iOfficeAI/OfficeCLI source code, with practical examples for every supported scenario.
How the query Command Works
Command Registration and CLI Options
The query verb is defined in src/officecli/CommandBuilder.GetQuery.cs. This file builds the command structure and parses options including --find, --compact, --fields, and --json.
When executed, the command creates a ResidentRequest with Command = "query" and sends it to the resident server if one is running. Otherwise, it opens the file directly.
officecli mydoc.docx query "paragraph" --json
Resident Server Handling
In src/officecli/ResidentServer.cs, the resident server receives the request through a command-dispatch switch (case "query"). It forwards the request to the appropriate IDocumentHandler.Query implementation—WordHandler, PowerPointHandler, or ExcelHandler depending on file type.
The handler returns a list of DocumentNode objects matching your selector.
Selector Processing with AttributeFilter
The core selector engine lives in src/officecli/Core/AttributeFilter.cs. The FilterSelector method parses CSS-like syntax and supports:
- Logical operators:
and,or,not - Attribute comparisons:
=,!=,>,< - Excel shorthand aliases:
boldexpands tofont.bold
The filter returns matching nodes plus any warnings for malformed selectors or unsupported properties.
CSS-Like Selector Syntax
Basic Element Selection
Select all elements of a given type using the element name.
# All paragraphs in a Word document
officecli mydoc.docx query "paragraph"
# All shapes in a PowerPoint presentation
officecli mydoc.pptx query "shape"
# All cells in an Excel workbook
officecli mydoc.xlsx query "cell"
Attribute Filtering
Filter elements by attributes using bracket notation.
# Headings with style "Heading1"
officecli mydoc.docx query "paragraph[style=Heading1]"
# Runs not using Arial font
officecli mydoc.docx query "run[font!=Arial]"
# Cells with width greater than 100
officecli myfile.xlsx query "cell[width>100]"
Logical Operators
Combine conditions with and, or, and not.
# Paragraphs that are Heading1 OR Heading2
officecli mydoc.docx query "paragraph[style=Heading1 or style=Heading2]"
# Bold runs NOT in Arial
officecli mydoc.docx query "run[font.bold=true and font.not(Arial)]"
Text Search with the --find Flag
The --find option provides case-insensitive substring matching on displayed text. This filtering happens after the selector engine returns its raw matches.
# Find paragraphs containing "Budget" (case-insensitive)
officecli mydoc.docx query "paragraph" --find "budget"
# Combine selector filtering with text search
officecli mydoc.docx query "paragraph[style=Heading1]" --find "executive summary"
Output Formats
JSON Output (--json)
Use --json for machine-readable output suitable for programmatic processing. The implementation in CommandBuilder.GetQuery.cs (lines 28-34) hydrates child nodes on-the-fly using handler.Get(path, depth: 1), ensuring the JSON structure matches a normal get --json response.
# Get all bold cells as JSON
officecli mydoc.xlsx query "cell[font.bold=true]" --json
{
"nodes": [
{
"type": "cell",
"path": "/sheet1/row5/cell2",
"text": "Total Revenue",
"format": {
"font.bold": true,
"fill.color": "#FFFFFF"
}
}
],
"total": 1
}
Compact Text Output (--compact)
The --compact flag produces a stable, line-oriented text format defined in CommandBuilder.GetQuery.cs (lines 81-95). This format is a stability contract with fixed column order, TAB separators, truncation marker …, and a final total: line—ideal for piping to other tools.
# Compact output for easy parsing
officecli mydoc.docx query "shape" --compact
shape /ppt/slide3/shape2 Text Box... total: 1
Adding Custom Fields (--fields)
Append extra attributes to compact output with the --fields option. The implementation looks up each field in the node's Format dictionary (lines 61-65).
# Include position and size data
officecli mydoc.pptx query "shape" --compact --fields x,y,width,height
shape /ppt/slide1/shape1 Title x=100 y=200 width=400 height=50 total: 1
Performance: Using the Resident Server
For repeated queries against the same document, start a resident server to eliminate file-open overhead.
# Start resident server (keeps file open in memory)
officecli open mydoc.docx
# Subsequent queries use the resident automatically
officecli query mydoc.docx "table"
officecli query mydoc.docx "paragraph[style=Heading1]" --json
officecli query mydoc.docx "shape" --find "diagram" --compact
The resident path is handled in ResidentServer.cs at lines 94-100, with proper exit code propagation for both success and failure cases.
Error Handling and Exit Codes
Malformed selectors or unsupported properties trigger warnings on stderr and a non-zero exit code. This applies consistently whether using the resident server or direct file access.
officecli mydoc.docx query "invalid[property//syntax]" # exits non-zero with warning
Summary
- Primary interface: CSS-like selectors processed by
AttributeFilter.FilterSelectorinsrc/officecli/Core/AttributeFilter.cs - Command definition:
src/officecli/CommandBuilder.GetQuery.cswith options--find,--compact,--fields,--json - Resident acceleration:
src/officecli/ResidentServer.csdispatches toIDocumentHandler.Queryimplementations - Output formats: JSON for machines, compact text for scripts (stability contract with TAB separators)
- Performance: Use
officecli opento enable resident server for repeated queries
Frequently Asked Questions
What file types does the query command support?
OfficeCLI supports Word (.docx), Excel (.xlsx), and PowerPoint (.pptx) files through their respective handlers: WordHandler, ExcelHandler, and PowerPointHandler. Each handler implements IDocumentHandler.Query to provide document-specific element enumeration.
How do I filter elements by their visible text content?
Use the -f/--find <text> flag. This performs case-insensitive substring matching after the selector engine returns matches. For example: officecli doc.docx query "paragraph" --find "confidential" finds all paragraphs containing "confidential" regardless of case.
What's the difference between --json and --compact output?
--json produces hierarchical, machine-readable output with full node metadata including children. --compact produces a stable, line-oriented text format with TAB-separated columns—designed for Unix-style piping and guaranteed not to change between versions. Add --fields to append custom attributes to compact output.
Can I use the query command in a CI/CD pipeline?
Yes. The command returns non-zero exit codes on failure (malformed selectors, file errors) and writes warnings to stderr, making it suitable for automated workflows. The --compact format's stability contract ensures your parsing logic won't break with updates.
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 →