How to Use CSS-Like Selectors and Boolean Operators with the OfficeCLI Query Command

The OfficeCLI query command supports CSS-like selectors with implicit AND logic for multiple attributes and explicit OR logic using comma separators, enabling precise filtering of Word, Excel, and PowerPoint document elements.

The iOfficeAI/OfficeCLI repository provides a cross-platform command-line tool for inspecting and manipulating Office Open XML documents. The query command implements a selector engine that parses CSS-like syntax to locate specific elements within .docx, .xlsx, and .pptx files, supporting complex boolean logic and pseudo-selectors.

Core Architecture and Source Files

The query functionality is implemented across several specialized handlers and a central filtering engine. Understanding these components helps clarify how boolean logic is evaluated.

Entry Point and Routing

In src/officecli/CommandBuilder.GetQuery.cs, the CLI parses the query verb and extracts the raw selector string. This file routes requests to format-specific handlers: WordHandler, ExcelHandler, or PowerPointHandler. Each handler converts the abstract selector into concrete OOXML path traversals.

Selector Engine

The AttributeFilter.cs file in src/officecli/Core/ contains the core parsing logic. The ParseSelector method tokenizes input into SelectorPart objects, evaluating attribute predicates and pseudo-selectors against the document's XML tree. This engine handles case-insensitive matching and supports regex-style operators.

Format-Specific Handlers

Concrete implementations reside in handler-specific query files:

Boolean Operators in OfficeCLI Queries

The selector engine supports two types of boolean logic for combining conditions: implicit conjunction within attribute brackets and explicit union through comma separation.

Implicit AND Logic

When you include multiple predicates inside a single bracket pair [ ], the engine treats them as logical AND operations. Every predicate must evaluate to true for the element to match.


# Rows where Score > 80 AND Year < 2025

officecli query document.xlsx 'row[Score>80 Year<2025]' --json

In AttributeFilter.cs, this creates a chained validation where each attribute constraint narrows the result set sequentially.

Explicit OR with Comma Separators

To achieve OR logic, separate complete selectors with commas (,). This performs a union of result sets, returning elements that match any of the specified selectors.


# All shapes OR pictures (union of both sets)

officecli query presentation.pptx 'shape, picture' --json

This syntax mirrors CSS group selectors and is processed by aggregating matches from each independent selector path.

Combining AND and OR

You can nest these approaches to create complex queries. Group conditions by placing multiple predicates inside brackets for AND logic, then use commas to OR between different selector groups.


# (Score > 80 AND Year < 2025) OR Status = "Closed"

officecli query data.xlsx 'row[Score>80 Year<2025], row[Status="Closed"]' --json

CSS-Like Selector Syntax

The query language implements standard CSS selector patterns adapted for Office document structures, including attribute filters, pseudo-selectors, and combinators.

Element and Attribute Selectors

Target specific OOXML elements using type names, then refine with attribute predicates inside brackets. Supported comparison operators include equality (=), inequality (!=), greater than (>), less than (<), and regex match (~=).


# Cells with value not equal to zero

officecli query sheet.xlsx 'cell[value!=0]' --json

# Cells whose formula contains "SUM" (regex)

officecli query budget.xlsx 'cell[formula~=SUM]' --json

Pseudo-Selectors for Content Filtering

The engine supports format-specific pseudo-selectors that operate on element content rather than attributes:

  • :contains("text") – Matches elements containing specific text
  • :empty – Matches elements with no content or whitespace-only content
  • :no-alt – Matches pictures lacking alternative text (PowerPoint specific)

# Paragraphs containing the word "Quarterly"

officecli query report.docx 'paragraph:contains("Quarterly")' --json

# Empty paragraphs or those with only whitespace

officecli query document.docx 'paragraph:empty, paragraph:contains("")' --json

Combinators for Hierarchy

Navigate document structure using CSS combinators:

  • Direct child (>) – Selects immediate children only
  • Descendant (space) – Selects elements at any depth below ancestor

# Shapes that are direct children of slides

officecli query deck.pptx 'slide > shape' --json

# Pictures anywhere inside slides (deep search)

officecli query deck.pptx 'slide picture' --json

Practical Code Examples

These runnable examples demonstrate common boolean and selector patterns against Office documents.

Filter Excel Rows with Numeric AND Conditions

officecli query sales.xlsx 'row[Revenue>1000 Status="Active"]' --json

Union Search Across Element Types

officecli query assets.pptx 'shape[fill=1E2761], picture[opacity>0.5]' --json

Content Search with Pseudo-Selectors


# Find cells containing formula errors

officecli query data.xlsx 'cell[formula]:contains("#REF!")' --json

Programmatic Result Counting


# Count matching shapes using JSON output

count=$(officecli query template.pptx 'shape[type=rectangle]' --json |
        jq '.data.results | length')
echo "Found $count rectangles"

Word Document Text Analysis


# Find paragraphs with specific formatting that contain keywords

officecli query contract.docx 'paragraph[style=Heading1]:contains("Clause")' --json

Summary

  • OfficeCLI query syntax uses CSS-like selectors to target elements in Word, Excel, and PowerPoint files via CommandBuilder.GetQuery.cs and AttributeFilter.cs.
  • Boolean AND is implicit when placing multiple predicates inside single brackets [attr1=value1 attr2=value2].
  • Boolean OR uses comma-separated selectors (selector1, selector2) to union result sets.
  • Pseudo-selectors like :contains(), :empty, and :no-alt filter based on content rather than attributes.
  • Combinators (> for direct children, space for descendants) navigate document hierarchies.
  • The engine is case-insensitive and supports regex matching via the ~= operator.

Frequently Asked Questions

How do I combine multiple conditions in an OfficeCLI query?

Use implicit AND by placing multiple predicates inside the same brackets: element[attr1=value1 attr2=value2]. For OR logic, separate complete selectors with commas: element1, element2. You can combine these approaches to create complex filters like row[Score>80 Year<2025], row[Status="Closed"].

What is the difference between space and > in OfficeCLI selectors?

The space (descendant combinator) selects elements at any depth within the ancestor, performing a deep search through nested structures. The > (direct child combinator) restricts matches to immediate children only, skipping nested groups or sub-elements. For example, slide > shape finds only top-level shapes, while slide shape finds shapes nested within groups.

Can I use regular expressions in OfficeCLI query selectors?

Yes, the regex match operator ~= allows pattern matching within attribute values. For example, cell[formula~=SUM] matches cells where the formula attribute contains the string "SUM" anywhere in its value. This is implemented in AttributeFilter.cs and works with any attribute predicate.

Which files handle the query parsing in OfficeCLI source code?

The query system spans three main areas: src/officecli/CommandBuilder.GetQuery.cs handles CLI argument parsing and handler dispatch; src/officecli/Core/AttributeFilter.cs implements the selector engine and boolean logic; and format-specific implementations in src/officecli/Handlers/Word/WordHandler.Query.cs, src/officecli/Handlers/Excel/ExcelHandler.Query.RowWhere.cs, and src/officecli/Handlers/Pptx/PowerPointHandler.Query.cs provide OOXML-specific element mappings.

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 →