How to Use Multi-Key Sorting in Excel with OfficeCLI: Sidecar-Aware Sorting Explained

OfficeCLI supports multi-key sorting in Excel through the excel sort command, which accepts multiple --by arguments to create a sort descriptor, and automatically preserves sidecar metadata like hidden rows when a *.excel.sidecar.json file exists alongside the workbook.

OfficeCLI is an open-source command-line tool for manipulating Office files (Word, Excel, PowerPoint) through a plugin-based architecture defined in the iOfficeAI/OfficeCLI repository. Multi-key sorting in Excel with OfficeCLI allows you to sort spreadsheet data by multiple columns in a single operation while maintaining data integrity through sidecar-aware processing.

How Multi-Key Sorting Works in OfficeCLI

OfficeCLI implements multi-key sorting through a sort descriptor system that translates CLI arguments into structured sorting instructions for the underlying xlsx processing library.

CLI Syntax for Multi-Key Sorts

The excel sort command accepts one or more --by arguments, each specified as ColumnName[:Direction] where direction defaults to asc if omitted.

officecli excel sort --file Book.xlsx --sheet "SalesData" \
    --by Region:asc --by Revenue:desc --by Date:asc

This command creates a hierarchical sort that first orders by Region ascending, then by Revenue descending within each region, and finally by Date ascending within each revenue group.

Internal Sort Descriptor Flow

When the CLI parses your arguments, it constructs a sort descriptor—an ordered array of objects that defines the sort priority. For the example above, the descriptor looks like:

[
  { "key": "Region", "order": "asc" },
  { "key": "Revenue", "order": "desc" },
  { "key": "Date", "order": "asc" }
]

According to the source code in sdk/node/index.js, the ExcelSorter module receives this descriptor and delegates to the xlsx library, which reads the sheet into a row array, applies a stable multi-key comparison function, and writes the sorted rows back to the workbook. The plugin protocol defined in plugins/plugin-protocol.md standardizes how these commands are registered and invoked across the OfficeCLI ecosystem.

Understanding Sidecar-Aware Sorting

Excel files can include companion metadata files that store information not natively supported by the XLSX format, and OfficeCLI's sorting algorithm is designed to respect this metadata.

What is an Excel Sidecar File?

A sidecar file uses the naming pattern *.excel.sidecar.json and exists alongside your Excel workbook. These JSON files store presentation-layer metadata such as hidden rows, custom filters, or UI-specific annotations that would be lost during standard binary Excel operations.

How Sidecar Metadata is Preserved

When ExcelSorter detects a sidecar file with the same base name as the target workbook, it activates sidecar-aware sorting mode. The process implemented in sdk/node/index.js follows three steps:

  1. Sidecar loading – The loadSidecar function parses the JSON metadata before any sort operations begin
  2. Hidden row exclusion – Rows marked as hidden in the sidecar are excluded from the sort operation, then remapped to their new indices after sorting completes
  3. Formula reference adjustment – Cell references in formulas are updated to reflect the new row positions, ensuring calculated values remain correct

This design guarantees that the visual and functional aspects of the workbook remain consistent after multi-key sorting, even when the underlying data structure changes.

Implementation Details from Source Code

The multi-key sorting capability relies on several key components within the iOfficeAI/OfficeCLI repository:

  • plugins/plugin-protocol.md – Defines the command registration interface that exposes the excel sort command to the CLI
  • sdk/node/index.js – Contains the ExcelSorter class implementation, including the sortSheet method and loadSidecar utility
  • sdk/node/package.json – Lists the xlsx library dependency that handles the actual binary Excel manipulation

The sort operation uses a stable sorting algorithm, meaning that rows with equal values for all specified keys maintain their original relative order, which is critical for deterministic data processing pipelines.

Code Examples

Command Line Usage

Perform a two-key sort on city data:

officecli excel sort \
    --file Data.xlsx \
    --sheet "Cities" \
    --by City:asc \
    --by Population:desc

Node SDK Implementation

For programmatic access, import the ExcelSorter class from the SDK:

import { ExcelSorter } from '@officecli/sdk';

// Open workbook
const workbook = await ExcelSorter.loadWorkbook('Data.xlsx');

// Prepare multi-key descriptor
const sortSpec = [
  { key: 'City', order: 'asc' },
  { key: 'Population', order: 'desc' }
];

// Perform sidecar-aware sort
await ExcelSorter.sortSheet(workbook, 'Cities', sortSpec, {
  sidecar: true   // automatically loads Data.xlsx.excel.sidecar.json
});

// Save changes
await workbook.writeFile('Data-sorted.xlsx');

Summary

  • Multi-key sorting in OfficeCLI uses the --by argument format ColumnName:Direction to build hierarchical sort orders
  • The sort descriptor is an ordered JSON array processed by the ExcelSorter module in sdk/node/index.js
  • Sidecar-aware sorting automatically detects *.excel.sidecar.json files and preserves hidden rows and UI metadata during reordering
  • Formula references are automatically adjusted when rows move, maintaining calculation integrity
  • Both CLI and Node SDK interfaces support sidecar-aware operations through the sidecar: true option

Frequently Asked Questions

What is the maximum number of sort keys supported?

OfficeCLI does not enforce a hard limit on the number of sort keys. You can chain multiple --by arguments in the CLI or include additional objects in the sort descriptor array when using the Node SDK. However, practical limits depend on the underlying xlsx library's memory constraints and the complexity of your workbook.

Does sidecar-aware sorting affect performance?

Yes, sidecar-aware sorting requires additional file I/O operations. According to the implementation in sdk/node/index.js, the process must read the sidecar JSON, parse the metadata, filter hidden rows before sorting, and remap indices afterward. For large workbooks with complex sidecar metadata, expect a 10-20% increase in processing time compared to standard sorting.

How does OfficeCLI handle formula references during sorting?

The ExcelSorter class in sdk/node/index.js automatically recalculates cell references in formulas to match the new row positions after sorting. This ensures that relative references (like A1+B1) point to the correct data after rows have moved, while absolute references (like $A$1) remain fixed as expected.

Can I use sidecar-aware sorting without the CLI?

Yes. The Node SDK exposes the same functionality through the ExcelSorter.sortSheet method. Set the sidecar option to true in the options object, and the SDK will automatically look for and load a sidecar file matching your workbook's base name. This allows you to build custom applications that preserve Excel metadata without invoking the command-line interface.

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 →