oportunidades 8
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-10-14 08:25:30 +02:00
parent 287e991486
commit ba1c0340ea
9112 changed files with 2199795 additions and 856 deletions
@@ -0,0 +1,503 @@
# Using artifact_tool APIs (JavaScript)
Library version: 2.8.58+
## Required Imports + Startup
Import existing workbook only when needed:
```js
import { FileBlob, SpreadsheetFile } from "@oai/artifact-tool";
const input = await FileBlob.load("path/to/input.xlsx");
const workbook = await SpreadsheetFile.importXlsx(input);
```
Import CSV text directly when the source or intermediate data is CSV:
```js
import fs from "node:fs/promises";
import { Workbook } from "@oai/artifact-tool";
const csvText = await fs.readFile("path/to/input.csv", "utf8");
const workbook = await Workbook.fromCSV(csvText, { sheetName: "Sheet1" });
```
Prefer `Workbook.fromCSV(...)` over hand-parsing CSV rows; clean or analyze CSV with Python/Node first only when needed.
CSV fields import as strings. Convert intended numeric/date columns before calculations; number formatting alone does not convert text to numbers.
Create new workbook:
```js
import fs from "node:fs/promises";
import { SpreadsheetFile, Workbook } from "@oai/artifact-tool";
const workbook = Workbook.create();
const sheet = workbook.worksheets.add("Inputs");
```
Final export:
```js
await fs.mkdir(outputDir, { recursive: true });
const output = await SpreadsheetFile.exportXlsx(workbook);
await output.save(`${outputDir}/output.xlsx`);
```
## Build Patterns
- Prefer block writes (`range.values`, `range.formulas`) over per-cell loops. Normally match the matrix shape to the target range (e.g. "D4:M4" → 1×10). To intentionally expand a larger matrix from an anchor, target a single cell or use `range.write(matrix)`.
- `range.values = [[value]]` repeats that value across the range; range.formulas does not broadcast a single formula. For merged ranges, write to the top-left cell or `mergedRange.values = [[value]]` where `mergedRange` is a single merged range.
- Seed scalar formulas once, then `fillDown()` / `fillRight()`. For dynamic-array formulas (`SEQUENCE`, `UNIQUE`, `FILTER`, `SORT`, `VSTACK`, `HSTACK`), write only the anchor cell and let the result spill after.
- Use `range.displayFormulas` plus `range.formulaInfos` when you need to understand a spill child or a data-table output cell.
- Formulas calculate automatically.
- Prefer real `Date` objects for sortable/charted/formula date columns.
- Number and date formats must be applied explicitly (for example `yyyy-mm-dd`).
- Use JSON-serializable values for non-Date cells: `string | number | boolean | null`.
- If a cell is intended to display literal text that begins with `=`, write it as a value prefixed with a single quote (for example `'=B2*C2`). This includes formula descriptions, validation examples, and labels; do not write these cells through `range.formulas`.
- Create every worksheet referenced by formulas before writing any cross-sheet formulas.
- Verify with `await workbook.inspect(...)`; use `workbook.help(...)` only when the quick surface below is insufficient.
## Conventions
- Use camelCase API names and option keys.
- Cell/range addressing: A1 notation (`sheet.getRange("A1:C10")`).
- Drawing anchors (`sheet.charts`, `sheet.shapes`, `sheet.images`): 0-based `{ row, col }`.
- Drawing offsets/extents use pixels (`rowOffsetPx`, `colOffsetPx`, `widthPx`, `heightPx`).
## API Discovery Policy (Strict)
- Use this quick API surface first.
- Use `workbook.help(...)` only when the supplied public documentation leaves a required operation unclear. Start with one bounded exact feature/path lookup, such as `range.dataValidation` or `chart.series.add`.
- If that lookup returns no useful match, one bounded reformulation is allowed. Stop after those two attempts; do not repeat similar queries, inspect package internals/prototypes/nearby tests, or invent enum values and setters. Use a documented equivalent that preserves the task.
- The examples below are alternatives for the relevant operation, not a discovery checklist to execute in full.
- `render` can be used to examine an existing workbook visually and for visual verifications.
## Supported Formulas
- Look up formula syntax with `fx.<formula>`, e.g. `workbook.help("fx.PMT", { include: "index,examples,notes", maxChars: 3000 })`. A help entry does not guarantee working calculation or Excel export.
- To browse a family of formulas, use `fx.*` with a category regex. Useful categories: `financial`, `math-trig`, `statistical`, `lookup-reference`, `logical`, `text`, `date-time`, `information`, `engineering`, `database`.
- For intent-based lookup, use a short natural query plus a narrow `search` regex of likely functions.
- Keep `maxChars` bounded; if results are noisy, narrow `search` rather than issuing many similar queries.
Useful `help` calls:
```js
console.log(workbook.help("shape.add", { include: "examples,notes" }).ndjson);
console.log(
workbook.help("*", {
search: "fill|borders|autofit",
include: "index,examples,notes",
maxChars: 6000,
}).ndjson,
);
console.log(workbook.help("fx.PMT", { include: "index,examples,notes" }).ndjson);
console.log(workbook.help("fx.*", { search: "financial", include: "index,examples", maxChars: 4000 }).ndjson);
console.log(workbook.help("fx.*", { search: "math-trig", include: "index,examples", maxChars: 4000 }).ndjson);
console.log(workbook.help("lookup with fallback", { search: "XLOOKUP|INDEX|MATCH|IFERROR", include: "index,examples,notes", maxChars: 4000 }).ndjson);
```
### Known formula/export limitations (not exhaustive)
If a formula fails, use a verified equivalent that preserves the intended result.
Known issues:
- Avoid `MAP`, `REDUCE`, `SCAN`, `MAKEARRAY`, `GROUPBY`, `PIVOTBY`. Use helper cells and supported scalar formulas;
- Prefix `XLOOKUP`, `TEXTJOIN`, `MINIFS`, `MAXIFS`, `IFS`, and `RANK.EQ` with `_xlfn.`, including nested calls: e.g. `'=_xlfn.TEXTJOIN(", ",TRUE,B2:C2)'`.
- For `LET`, `LAMBDA`, `BYROW`, and `BYCOL`, prefix function names with `_xlfn.` and every LET/LAMBDA local-variable declaration and reference with `_xlpm.`.
- PivotTable APIs exist, but XLSX export is unreliable; use formula summaries.
- `COUNTIF` / `COUNTIFS` with an empty-string criterion can miss blank cells, even in bounded ranges. For unconditional blank counts, use `COUNTBLANK(range)`.
## Reading existing/imported workbooks
- On existing/imported workbooks, get a compact summary via `inspect` to understand what already exists and where.
- Prefer `inspect(...)` for workbook understanding and discovery across broad areas.
- Prefer direct getters like `range.formulas` when you already know the target range and need the exact rectangular formula matrix.
- If formula locations are unknown, prefer `inspect({ kind: "formula", ... })` over reading `range.formulas` across a very large area.
- Prefer to set `maxChars`, `tableMaxRows`, `tableMaxCols`, and/or `maxResults` to prevent large dumps of data.
- For suspicious or high-impact outputs, use `workbook.trace("Sheet!A1")` to audit the dependency tree from final output/check cell back to source cells. Trace output can be large, so summarize by depth/node count before logging.
### Inspect for workbook understanding
- Compact summary:
```js
await wb.inspect({
kind: "workbook,sheet,table",
maxChars: 6000,
tableMaxRows: 6,
tableMaxCols: 6,
tableMaxCellChars: 80,
});
```
- Quick overview of sheet ids and names: `await wb.inspect({ kind: "sheet", include: "id,name" })`
- Formula discovery in a targeted area: `await wb.inspect({ kind: "formula", sheetId: firstSheetName, range: "A1:Z30", maxChars: 2500, options: {maxResults:50} })`
- Checking existing styles in a targeted area: `await wb.inspect({ kind: "computedStyle", sheetId: firstSheetName, range: "A1:E10", maxChars: 2500 })`
- Common `kind` tokens: `workbook`, `sheet`, `table`, `region`, `match`, `formula`, `thread`, `computedStyle`, `definedName`, `drawing`
- Inspects can also be used to zoom in on specific areas, especially for target edits:
```js
await wb.inspect({
kind: "region",
sheetId: firstSheetName,
range: "A1:Z30",
maxChars: 2500,
});
```
- Inspect output may include JSON records with `"id"` values (for example `"ws/r5qsk5"`), which you can resolve back to workbook objects with `wb.resolve(...)`:
- `wb.resolve("ws/...")` -> worksheet
- `wb.resolve("th/...")` -> comment thread
## Known Gotchas (Do not repeat)
- Do not set undocumented attributes on remote objects.
- `Workbook.create()` starts with no sheets; add one before calling `getActiveWorksheet()`.
- Create every worksheet referenced by formulas before writing cross-sheet formulas.
- Prefer bounded formula ranges with explicit start/end rows, e.g. `$A$6:$A$205`. Full-column references such as `A:A`, `$A:$A`, or `Sheet!B:B` can be truncated to each column's populated extent: unequal extents can make `COUNTIFS` / `SUMIFS` return `#VALUE!`, and `ROWS` / `INDEX` can differ from Excel.
- If export fails, isolate the cause by checkpoint-export after major blocks to isolate the cause: base sheets, values/formulas, formatting, conditional formatting, tables, charts/rendering. For charts, first simplify optional styling first: nested border configs, custom chart axis/series mutations, broad autofit/formatting, then nonessential drawings.
## Additional feature-specific notes
### Merging cells
- `range.merge()` merges the target range into one cell; `range.merge(true)` merges across each row in the target range.
- `range.unmerge()` reverses a merge.
For example:
```js
const range = sheet.getRange("I23:N24");
range.merge();
range.values = [["Source note spanning the recommendation panel"]];
```
## Quick API Surface (High-Value + Common)
### Core workbook/file APIs
- `import { FileBlob, SpreadsheetFile, Workbook } from "@oai/artifact-tool"`
- `const workbook = Workbook.create()` to create an empty workbook
- `const sheet = workbook.worksheets.add("Sheet1")` to add a sheet
- `const workbook = await SpreadsheetFile.importXlsx(arrayBufferOrFileBlob)`
- `const xlsx = await SpreadsheetFile.exportXlsx(workbook); await xlsx.save("output.xlsx")`
- `const inspect = await workbook.inspect({ kind: "sheet", include: "id,name", sheetId, range: "A1:C10" })`
- `const help = workbook.help("worksheet.getRange", { include: "index,examples" })`
- Preferred: `const preview = await workbook.render({ sheetName: "Sheet1", autoCrop: "all", scale: 1, format: "png" })`
- To get the bytes and/or save the blob to file:
```js
const previewBytes = new Uint8Array(await preview.arrayBuffer());
await fs.writeFile(`${outputDir}/preview.png`, previewBytes);
```
- `const workbook = await Workbook.fromCSV(csvText, { sheetName: "Sheet1" })`
- `await workbook.fromCSV(csvText, { sheetName: "ImportedData" })` requires an empty workbook; it does not append CSV to a populated workbook. Prefer static `Workbook.fromCSV(...)`.
### Worksheet selection/creation
- `workbook.worksheets.add(name)`
- `workbook.worksheets.getItem(name)`
- `workbook.worksheets.getItemAt(index)`
- `workbook.worksheets.getActiveWorksheet()` (only after at least one sheet exists)
### Worksheet operations
- `sheet.getRange("A1:C10")`, `sheet.getRangeByIndexes(startRow, startCol, rowCount, colCount)`, `sheet.getCell(row, col)`
- `sheet.getUsedRange(valuesOnly?)`
- `sheet.mergeCells("A1:C1")`, `sheet.unmergeCells("A1:C1")`
- `sheet.freezePanes.freezeRows(rowCount)`, `sheet.freezePanes.freezeColumns(columnCount)`, `sheet.freezePanes.unfreeze()`
- `sheet.tabColor = "#1F4E78"` sets the worksheet tab color; the getter returns a `Color` object.
- `sheet.tables`, `sheet.charts`, `sheet.sparklineGroups` (`sheet.sparklines` alias), `sheet.shapes`, `sheet.images`
- `sheet.showGridLines = false`
- `sheet.dataTables`, `sheet.conditionalFormattings`, `sheet.dataValidations`
- `sheet.deleteAllDrawings()` removes all drawings, including charts, shapes, and images.
### Range values/formulas
- `const range = sheet.getRange("A1:C10")`
- `range.values = [[...], ...]` (2D matrix of values).
- `range.formulas = [["=..."], ...]`
- `range.formulasR1C1 = [["=RC[-1]*2"]]`
- To read: `range.values` / `range.formulas` / `range.displayFormulas` / `range.formulaInfos` (for spill/array formulas)
- `range.write(matrixOrPayload)` (auto-sizes/spills from anchor as needed)
- `range.writeValues(matrixOrRows)`
- `range.fillDown()`, `range.fillRight()`
- `sheet.getRange("D2").formulas = [["=..."]]`
- `sheet.getRange("D2:D200").fillDown()`
- `range.clear({ applyTo: "contents" | "formats" | "all" })` clears cell contents, formatting, or both; drawings remain.
- `range.copyFrom(sourceRange, "values" | "formulas" | "all")`. Prefer matching shapes; a single-cell value source can broadcast across a larger destination.
- `range.copyTo(destRange, "values" | "formulas" | "all")`
- `range.offset(rowOffset, colOffset)`, `range.resize(rowCount, columnCount)`, `range.getCurrentRegion()`, `range.getRow(i)`, `range.getColumn(j)`
- `range.getRangeByIndexes(startRow, startCol, rowCount, colCount)`, `range.getCell(row, col)` (relative to the range)
- `range.merge()`, `range.merge(true)` to merge across, `range.unmerge()`
### Formatting
- `range.format` supports `fill`, `font`, `numberFormat`, `borders`, alignments, `wrapText`
- `range.format.verticalAlignment = "center"` maps to Excel Middle Align
- `range.format.autofitColumns()`, `range.format.autofitRows()`
- Excel unit sizing: `range.format.columnWidth = 18`, `range.format.rowHeight = 24`
- Pixel sizing: `range.format.columnWidthPx = 120`, `range.format.rowHeightPx = 24`
- `range.setNumberFormat("yyyy-mm-dd")`
- `range.format.numberFormat = [["0"], ["0.00"], ["@"]]`
- Borders: There are two ways to set borders on a range (1) simple form (2) per edge form. Example:
```js
// (1) Preferred simple form
// `preset` can be "none" | "outside" | "inside" | "all" | "doubleBottom"
// "outside" will just set borders on the outside edges of the range.
// `style` are Excel/OpenXML-style names such as "thin", "medium", "thick", "dashed", and "dotted".
range.format.borders = { preset: "all", style: "thin", color: "#D9D9D9" };
// (2) Per-edge form. Use top/bottom/left/right, not edgeTop/edgeBottom/etc.
// Format: {style?: string; color?: ColorConfig; weight?: number;}
// Prefer setting `style` over `weight` unless you want granular control.
range.format.borders = {
insideHorizontal: { style: "thin", color: "#D9D9D9" },
insideVertical: { style: "medium", color: "#D9D9D9" },
top: { style: "thick", color: "#D9D9D9" },
bottom: { style: "dashed", color: "#D9D9D9" },
left: { style: "dotted", color: "#D9D9D9" },
right: { style: "thin", color: "#D9D9D9" },
};
```
### Data Validation
- `range.dataValidation = { rule: { type: "list", formula1: "Categories!$A$2:$A$4" } }`
- `range.dataValidation = { rule: { type: "list", values: ["Not Started", "In Progress"] } }`
- `sheet.dataValidations.add({ range: "B2:B100", rule: { type: "whole", operator: "between", formula1: 1, formula2: 10 } })`
### Conditional formatting
- Use `range.conditionalFormats.add(ruleType, ConditionalFormatConfig);`.
- Use `range.conditionalFormats.add(ruleType, {operator, formula, format});`. Choose ruleType, operator, color, and style strings from the inline types below.
```
type ConditionalFormatRuleType =
| "cellIs" | "CellValue" | "Custom" | "expression"
| "colorScale" | "dataBar" | "iconSet"
| "containsText" | "notContainsText" | "beginsWith" | "endsWith"
| "containsBlanks" | "notContainsBlanks" | "containsErrors" | "notContainsErrors"
| "duplicateValues" | "uniqueValues" | "timePeriod" | "top10" | "aboveAverage";
type CellIsOperator =
| "greaterThan"
| "greaterThanOrEqual"
| "lessThan"
| "lessThanOrEqual"
| "equal"
| "notEqual"
| "between"
| "notBetween";
type ConditionalFormatConfig =
| { operator: CellIsOperator; formula: string | number | Array<string | number>; format?: DifferentialFormatConfig }
| { formula: string | number; format?: DifferentialFormatConfig }
| { colors?: ColorConfig[]; thresholds?: CfvoInput[] }
| { color?: ColorConfig; thresholds?: CfvoInput[]; gradient?: boolean }
| { iconSet: string; showValue?: boolean; reverse?: boolean; thresholds?: CfvoInput[] }
| { text: string; format?: DifferentialFormatConfig }
| { timePeriod: "yesterday" | "today" | "tomorrow" | "last7Days" | "lastWeek" | "thisWeek" | "nextWeek" | "lastMonth" | "thisMonth" | "nextMonth"; format?: DifferentialFormatConfig }
| { rank?: number; percent?: boolean; bottom?: boolean; format?: DifferentialFormatConfig }
| { aboveAverage?: boolean; equalAverage?: boolean; stdDev?: number; format?: DifferentialFormatConfig };
type DifferentialFormatConfig = {
fill?: FillConfig;
font?: { bold?: boolean; italic?: boolean; color?: ColorConfig };
border?: RangeBordersConfig; // Per-edge top/bottom/left/right only; presets are ignored here.
numberFormat?: string;
};
type CfvoInput =
| "min"
| "max"
| number
| `${number}%`
| { type: "min" | "max" | "num" | "percent" | "percentile"; value?: string | number };
```
- Rule types (`ConditionalFormatRuleType`): "cellIs" | "CellValue" | "Custom" | "expression"
| "colorScale" | "dataBar" | "iconSet"
| "containsText" | "notContainsText" | "beginsWith" | "endsWith"
| "containsBlanks" | "notContainsBlanks" | "containsErrors" | "notContainsErrors"
| "duplicateValues" | "uniqueValues" | "timePeriod" | "top10" | "aboveAverage";
- XLSX `iconSet` names: `3Arrows`, `4Arrows`, `5Arrows`, `3ArrowsGray`, `4ArrowsGray`, `5ArrowsGray`, `3TrafficLights1`, `3Signs`, `4RedToBlack`, `3TrafficLights2`, `4TrafficLights`, `3Symbols`, `3Flags`, `3Symbols2`, `5Quarters`, `4Rating`, `5Rating`. Avoid `3Stars`, `3Triangles`, and `5Boxes`: their current XLSX serialization is not reliable.
- Custom conditional formatting: `range.conditionalFormats.addCustom(expression, {fill, font, border});`
- `range.conditionalFormats.deleteAll()` / `range.conditionalFormats.clear()`
```js
const grid = sheet.getRange("B2:J10");
grid.conditionalFormats.add("colorScale", {
colors: ["#2563EB", "#FDE047", "#DC2626"],
thresholds: ["min", { type: "percentile", value: 50 }, "max"]
});
```
### Tables
- When adding new tables, set explicit unique names (`TasksTable`, `SummaryTable`).
- Do not overlap tables; the API does not reject overlaps. Check existing table ranges in the initial compact `inspect` summary before adding one.
- `const table = sheet.tables.add("A1:H200", true, "TasksTable")`
- `table.rows.add(null, [[...], ...])`, `table.getDataRows()`, `table.getHeaderRowRange()`
- Read tables: `sheet.tables.items` -> `Table[]`
- Set + Getters: `table.name`, `table.style`, `table.showHeaders`
- Toggles for table utilities (set/get): `table.showTotals`, `table.showBandedColumns = true`, `table.showFilterButton`
- `table.delete()`
### Images
- `sheet.images.add({dataUrl: "data:image/png;base64,...", anchor: {from: { row: 1, col: 2 }, extent: { widthPx: 160, heightPx: 120 }}})`
### Threaded Comments
This is the API to create a threaded comment in Excel, which requires a user-visible author.
- Required: Before adding a comment, create its visible author with `workbook.comments.setSelf({"displayName": <user_display_string>})`, where `<user_display_string>` is a string such as "User"
- Create a new thread with a single comment: `const thread = workbook.comments.addThread({"cell": sheet.getRange("E2")}, "Source: <website>")`
- To reply to a threaded comment: `thread.addReply("This is a reply to the comment")`
- To resolve/re-open a thread: `thread.resolve()`, `thread.reopen()`
### Charts
- Place charts in reserved blank areas with gutter rows/columns; do not cover data.
- Prefer range-backed charts so source edits update the chart. Headers are detected when the first row contains text and no numeric cells.
#### Fast-chart path
- For contiguous data: pass categories first, then one column per series:
```js
sheet.getRange("F4:H6").values = [
["Month", "Revenue", "EBITDA"],
["Jan", 100, 10],
["Feb", 120, 18],
];
const chart = sheet.charts.add("line", sheet.getRange("F4:H6"));
```
- For nonadjacent columns: pass equal-height, single-column ranges with categories first:
```js
const chart = sheet.charts.add("bar", [
sheet.getRange("A1:A10"),
sheet.getRange("D1:D10"),
sheet.getRange("G1:G10"),
]);
chart.series.items[0].fill = "#F472B6";
```
- Both paths create source-cell references and show a bottom legend. Apply requested formatting once after creation:
```js
chart.setPosition("J4", "Q20"); // always set
const fontFamily = "Arial";
chart.title = "Revenue and EBITDA Trend";
chart.titleTextStyle.fontSize = 12;
chart.titleTextStyle.typeface = fontFamily;
chart.legend = { position: "top", textStyle: { typeface: fontFamily } };
chart.xAxis = { axisType: "textAxis", textStyle: { typeface: fontFamily, fontSize: 10 } };
// Number formatting on chart axis must be set separately even if the source range is already formatted.
chart.yAxis = { numberFormatCode: "$#,##0", numberFormatSourceLinked: false, textStyle: { typeface: fontFamily }, tickLabelInterval: 2 };
chart.xAxis.title.text = "Month";
chart.yAxis.title.text = "Revenue and EBITDA";
```
- Chart `textStyle.fontSize` uses pixels; `typeface` sets the family. Style axes, legend, and titles separately (`xAxis.textStyle`, `yAxis.textStyle`, `legend.textStyle`, `titleTextStyle`); cell fonts do not configure chart fonts.
- Only set/style intended titles; styling an absent title can create a placeholder.
- For custom axis formats, set `numberFormatSourceLinked: false`. For $M labels, use `$0.0,,"M"` for dollars, `$0.0,"M"` for thousands, or `$0.0"M"` for millions. Fix formatting without changing source data.
- `chart.setData(range)` replaces categories/series but preserves title, legend, and axes. Apply series styling after binding data.
- For month/date labels, use helper cells containing strings such as `Jan 2025`; date-axis formats may show serial numbers in previews.
- Inspect series through `chart.series.items`; source bindings are `series.formula` and `series.categoryFormula`.
- Additional chart getters: `chart.type`, `chart.title.text`, `chart.categories` (may be empty for range-backed charts; inspect series references).
- Collection methods: `sheet.charts.getItemOrNullObject("Chart 1")`, `sheet.charts.deleteAll()`.
- XLSX chart types: `"bar" | "line" | "area" | "pie" | "doughnut" | "scatter" | "bubble" | "radar" | "stock"`.
- `"treemap"`, `"sunburst"`, `"histogram"`, `"boxWhisker"`, `"waterfall"`, `"funnel"`, and `"map"` are accepted by the API but omitted from XLSX exports in this runtime. Do not use them for Excel deliverables.
### Sparklines
```js
const group = sheet.sparklineGroups.add({
type: "line",
targetRange: "E2:E4",
sourceData: "A2:C4",
seriesColor: "#2563EB",
markers: { high: true, low: true },
});
```
- Sparkline type is a string. Use the public options documented below. Do not set internal/proto enum values for empty-cell display or axis modes; if a required option is not documented for the selected runtime, follow the bounded discovery policy.
- Avoid `dateAxisRange` for XLSX output; it is not serialized. Keep automatic axis limits: `manualMin` / `manualMax` alone do not select custom limits in Excel.
- Sparkline Inline Type:
```
type SparklineConfig = {
type: "line" | "column" | "stacked";
targetRange: Range | string;
sourceData: Range | string;
lineWeight?: number;
displayHidden?: boolean;
seriesColor?: ColorConfig;
negativeColor?: ColorConfig;
axisColor?: ColorConfig;
markersColor?: ColorConfig;
firstMarkerColor?: ColorConfig;
lastMarkerColor?: ColorConfig;
highMarkerColor?: ColorConfig;
lowMarkerColor?: ColorConfig;
markers?: SparklineMarkersOptions;
axis?: SparklineAxisOptions;
};
type SparklineMarkersOptions = {
show?: boolean;
high?: boolean;
low?: boolean;
first?: boolean;
last?: boolean;
negative?: boolean;
};
type SparklineAxisOptions = {
showAxis?: boolean;
rightToLeft?: boolean;
};
```
- Range Alias: `const group = targetRange.sparklines.add(type, sourceRange, sparklineConfig);`
- Edit And Delete
```js
group.seriesColor = "#2563EB";
group.markers.high = true;
group.axis.showAxis = true;
sheet.sparklineGroups.delete(group);
sheet.sparklineGroups.deleteAll();
```
### Help / Grep
Use `workbook.help(...)` primarily for obscure/advanced surfaces (for example deep chart axis settings, unusual drawing configs, pivot APIs, or uncommon option schemas).
- `workbook.help("enum.ShapeGeometry", { include: "index,notes" }).ndjson`
- `workbook.help("enum.*", { search: "ShapeGeometry|LineStyle", include: "index" }).ndjson`
- `workbook.help("shape.add", { include: "examples,notes" }).ndjson`
- `workbook.help("fx.RATE", { include: "index,examples,notes" }).ndjson`
- `workbook.help("cash flow return rate", { search: "IRR|XIRR|NPV|XNPV", include: "index,examples,notes", maxChars: 4000 }).ndjson`
- `workbook.help("*", { search: "fill|borders|autofit", include: "index,examples,notes", maxChars: 6000 }).ndjson`
### Trace
For tracing the full tree of how a formula is calculated, `workbook.trace("Sheet!A1")` is available. For complex formulas, the full tree can be extremely large, so output should be capped or outputted to a separate temp file (never dump raw traces). It takes only a cell reference.
### JavaScript example snippet (runnable)
```js
import fs from "node:fs/promises";
import { SpreadsheetFile, Workbook } from "@oai/artifact-tool";
const fontFamily = "Arial";
const outputDir = "output";
await fs.mkdir(outputDir, { recursive: true });
const workbook = Workbook.create();
const sheet = workbook.worksheets.add("Summary");
sheet.getRange("A1:C4").values = [
["Month", "Revenue", "EBITDA"],
["Jan", 100, 10],
["Feb", 120, 18],
["Mar", 130, 22],
];
sheet.getRange("D1").values = [["Margin"]];
sheet.getRange("D2").formulas = [["=C2/B2"]];
sheet.getRange("D2:D4").fillDown();
sheet.getRange("A1:G4").format.font = { name: fontFamily, size: 11 };
sheet.getRange("A1:D1").format = {
fill: "#0F766E",
font: { name: fontFamily, bold: true, color: "#FFFFFF" },
};
sheet.getRange("B2:C4").format.numberFormat = "$#,##0";
sheet.getRange("D2:D4").format.numberFormat = "0.0%";
// Helper range links to source cells so edits update the chart.
sheet.getRange("F1:G1").values = [["Month", "Revenue"]];
sheet.getRange("F2:G2").formulas = [["=A2", "=B2"]];
sheet.getRange("F2:G4").fillDown();
const chart = sheet.charts.add("line", sheet.getRange("F1:G4"));
chart.title = "Revenue Trend";
chart.titleTextStyle.typeface = fontFamily;
chart.hasLegend = false;
chart.xAxis = { axisType: "textAxis", textStyle: { typeface: fontFamily } };
chart.yAxis = { numberFormatCode: "$#,##0", numberFormatSourceLinked: false, textStyle: { typeface: fontFamily } };
chart.setPosition("I1", "P15");
const preview = await workbook.render({
sheetName: "Summary",
autoCrop: "all",
scale: 1,
format: "png",
});
await fs.writeFile(`${outputDir}/summary.png`, new Uint8Array(await preview.arrayBuffer()));
const xlsx = await SpreadsheetFile.exportXlsx(workbook);
await xlsx.save(`${outputDir}/summary.xlsx`);
```
@@ -0,0 +1,210 @@
# Workbook API Docs
Use the workbook facades to create and edit Excel-style workbooks in TypeScript,
including worksheets, ranges, formulas, tables, charts, drawings, comments,
named ranges, import/export helpers, inspection, and recorded patches.
## Conventions
- **A1 addresses for ranges**: use `sheet.getRange("A1:B2")` for A1 ranges.
Use `getRangeByIndexes(row, column, rowCount, columnCount)` and
`getCell(row, column)` for zero-based index access.
- **Matrices are row-major**: range values and formulas use `rows x columns`
arrays. Single-row and single-column ranges accept one-dimensional arrays.
- **Formulas include `=`**: assigning a string starting with `=` through
`values` stores a formula; prefix with `'` to store a literal leading `=`.
- **Use `write` for shape-matched writes**: `range.write(...)` can resize from
the target top-left cell.
- **Record user edits**: wrap edits in `workbook.record(() => { ... })` when a
patch, id map, or CRDT update is needed.
- **Inspect before editing imported workbooks**: use `inspect`, `findCells`,
and `resolve` to locate exact sheets, tables, charts, and threads.
- **Config-first creation**: prefer worksheet/range/table/chart config objects
where available.
- **PDF export**: `workbook.export({ format: "pdf" })` exports all worksheets.
Set `pageSizing: "uniform"` for equal page sizes.
## Quick Start
```ts
const workbook = Workbook.create();
const sheet = workbook.worksheets.add("Data");
sheet.getRange("A1:C4").values = [
["Region", "Q1", "Q2"],
["North", 10, 12],
["South", 8, 9],
["Total", null, null],
];
sheet.getRange("B4:C4").formulas = [["=SUM(B2:B3)", "=SUM(C2:C3)"]];
workbook.recalculate();
const table = sheet.tables.add("A1:C4", true, "DataTable");
table.rows.add(null, [["West", 7, 11]]);
const chart = sheet.charts.add("bar", {
from: { row: 1, col: 4 },
extent: { widthPx: 420, heightPx: 260 },
});
chart.title = "Quarterly values";
chart.categories = ["North", "South", "West"];
const series = chart.series.add("Q1");
series.values = [10, 8, 7];
series.categories = chart.categories;
const preview = await workbook.export({
sheet,
range: "A1:C5",
format: "png",
scale: 2,
});
const layoutBlob = await workbook.export({
sheet,
range: "A1:C5",
format: "layout",
});
const pdfBlob = await workbook.export({ format: "pdf" });
const uniformPdfBlob = await workbook.export({
format: "pdf",
pageSizing: "uniform",
headers: true,
});
const proto = workbook.toProto();
```
## Load Existing Workbook Data
```ts
const workbook = Workbook.load(proto, { validate: true });
const before = await workbook.inspect({
kind: "sheet,table,formula,chart,thread",
search: "Revenue",
maxChars: 8000,
});
const sheet = workbook.resolve(sheetAnchorId);
sheet.getRange("B2").values = [["Updated"]];
const after = await workbook.inspect({
target: { id: sheetAnchorId, beforeLines: 1, afterLines: 6 },
kind: "sheet,table",
});
```
## Recorded Edit
```ts
const { result, patch, idMap, crdtUpdateV2 } = workbook.record(() => {
const sheet = workbook.worksheets.getItem("Data");
sheet.getRange("A1:B2").values = [
["Name", "Value"],
["A", 1],
];
return sheet.tables.add("A1:B2", true, "DataTable");
});
```
`record` hydrates collaborative state when needed and returns the callback
result, a workbook patch, created-id aliases, and a merged CRDT update when
collaborative edits occurred.
## Core API Sequence
- Create workbooks with `Workbook.create()` and load with
`Workbook.load(proto, { validate })`.
- Import simple tabular data with `Workbook.fromCSV(...)`,
`workbook.fromCSV(...)`, and `Workbook.fromMarkdown(...)`.
- Add or select sheets with `workbook.worksheets.add(...)`, `getItem(...)`,
`getActiveWorksheet()`, and
`setActiveWorksheet(...)`.
- Edit data with `sheet.getRange("A1:B2").values`, `.formulas`,
`.formulasR1C1`, `.write(...)`, `.clear(...)`, `.merge(...)`, and
`.copyFrom(...)`.
- Add tables with `sheet.tables.add(range, hasHeaders, name)` and edit rows,
columns, styles, totals, and filters on the table facade.
- Add charts, images, shapes, sparklines, conditional formats, data
validations, freeze panes, pivot tables, slicers, comments, notes, and names
through their worksheet/workbook facades.
- Recalculate formulas with `workbook.recalculate()` and inspect dependencies
with `workbook.trace("Sheet!A1")`.
- Inspect imported workbooks with `workbook.inspect(...)`, `findCells(...)`,
`help(...)`, and `resolve(...)`.
- Render previews with `workbook.render(...)` or `workbook.export(...)`.
- Export all worksheets as PDF with `workbook.export({ format: "pdf" })`.
Pass `sheet`, `sheetName`, or `sheetIndex` to export one worksheet.
- Set PDF `pageSizing` to `"per-sheet"` (default) or `"uniform"`.
- Export grid and style evidence with `workbook.export({ format: "layout" })`
when template reconstruction needs cell frames, style regions, merged ranges,
validations, defined names, and drawing anchors.
- Serialize workbook data with `workbook.toProto()`.
## Output Map
| Output | API | Result |
| --------------- | --------------------------------------------- | --------------------------------------------- |
| Serialized data | `workbook.toProto()` | Serializable workbook proto |
| Inspect records | `await workbook.inspect(options)` | Structured records and NDJSON |
| Cell search | `workbook.findCells(options)` | Matches with sheet/address/value/formula info |
| Help records | `workbook.help(query, options)` | Bounded NDJSON API help records |
| Image preview | `workbook.export({ format: "png" })` | Workbook/sheet/range render blob |
| PDF | `workbook.export({ format: "pdf" })` | PDF `Blob` |
| Layout JSON | `workbook.export({ format: "layout" })` | Typed grid and style evidence |
| Native workbook | `workbook.export({ format: "xlsx" })` | Editable XLSX `Blob` |
| Render blob | `workbook.render(options)` | Render-provider blob |
| HTML table | `workbook.toHTML(sheetIndex, range, options)` | Excel/Sheets-compatible HTML |
| Recorded patch | `workbook.record(fn)` | `{ result, patch, idMap, crdtUpdateV2 }` |
## Minimal Patterns
```ts
// Data + formulas.
const workbook = Workbook.create();
const sheet = workbook.worksheets.add("Calc");
sheet.getRange("A1:B2").values = [
[2, 3],
[5, 7],
];
sheet.getRange("C1:C2").formulas = [["=A1+B1"], ["=A2+B2"]];
workbook.recalculate();
```
```ts
// Inspect, resolve, edit, re-inspect.
const snapshot = await workbook.inspect({
kind: "sheet,table,formula,thread,chart",
search: "Status",
});
const sheet = workbook.resolve(sheetAnchorId);
sheet.getRange("B2").values = [["Closed"]];
const updated = await workbook.inspect({
target: { id: sheetAnchorId },
kind: "sheet,table",
});
```
## Reference Map
- [`references/workbook.spec.md`](./references/workbook.spec.md) -
`Workbook` create/load/import/export/inspect/help/record surface.
- [`references/worksheets.spec.md`](./references/worksheets.spec.md) -
worksheet collection and worksheet facade.
- [`references/ranges.spec.md`](./references/ranges.spec.md) - values,
formulas, indexing, formatting, clearing, merging, fill, and copy.
- [`references/tables.spec.md`](./references/tables.spec.md) - worksheet
tables, rows, columns, headers, totals, and recorded patches.
- [`references/pivot-tables.spec.md`](./references/pivot-tables.spec.md) -
pivot creation, calculations, layout, filtering, and editing.
- [`references/formulas.spec.md`](./references/formulas.spec.md) -
recalculation, formula assignment, dynamic arrays, trace, and names.
- [`references/formatting.spec.md`](./references/formatting.spec.md) - range
formats, workbook theme, conditional formatting, data validation, and freeze
panes.
- [`references/charts-drawings.spec.md`](./references/charts-drawings.spec.md)
- worksheet charts, images, shapes, sparklines, and drawing layout.
- [`references/comments-notes-names.spec.md`](./references/comments-notes-names.spec.md)
- comments, notes, workbook-scoped names, and sheet-scoped names.
- [`references/inspect-help.md`](./references/inspect-help.md) - inspect,
resolve, findCells, and help workflows.
- [`references/import-export.md`](./references/import-export.md) - CSV,
Markdown, HTML, image import, rendering, export, and Google Sheets adapters.
@@ -0,0 +1,264 @@
# Charts And Drawings
Worksheets expose drawing collections for charts, images, and shapes.
## Charts
```ts
const chart = sheet.charts.add("bar", {
from: { row: 1, col: 4 },
extent: { widthPx: 420, heightPx: 260 },
});
chart.title = "Values";
chart.categories = ["A", "B", "C"];
const series = chart.series.add("Value");
series.values = [3, 5, 8];
series.categories = chart.categories;
```
Charts can be resolved from inspect anchors:
```ts
const chart = workbook.resolve("ch/<chartId>");
```
### Edit The Chart Frame
```ts
chart.roundedCorners = true;
chart.roundedCorners = false;
chart.roundedCorners = null;
const roundedCorners = chart.roundedCorners;
```
### Edit Chart Family Options
```ts
histogram.apply({ histogramOptions: { binCount: 8, underflow: 0, overflow: 30 } });
histogram.apply({ histogramOptions: { binWidth: null, binCount: null } });
histogram.apply({ histogramOptions: { underflow: null, overflow: null } });
bubble.bubbleOptions = { scale: 150, sizeRepresents: "width" };
bubble.bubbleOptions = { scale: null, sizeRepresents: null };
const settings = bubble.bubbleOptions;
```
[Chart family options](../../../presentations/api/references/charts.spec.md#chart-family-options)
### Edit Error Bars
```ts
const errorBars = chart.series.getItemAt(0).errorBars;
errorBars.apply("y", { type: "fixedValue", value: 2 });
errorBars.apply("y", {
display: "both",
endStyle: "cap",
line: { fill: "accent1", width: 1.5, style: "solid" },
});
const editableDirections = errorBars.directions;
const settings = errorBars.get("y");
errorBars.apply("y", { line: { width: null } });
errorBars.apply("y", { type: "none" });
```
### Edit Individual Trendlines
```ts
const trendlines = chart.series.getItemAt(0).trendlines;
const types = trendlines.supportedTypes;
const trendline = trendlines.add("linear", { name: "Forecast" });
trendline.apply({
forecastForward: 2,
displayEquation: true,
line: { fill: "accent2", width: 2, style: "dashed" },
label: {
numberFormatCode: "0.00",
numberFormatSourceLinked: false,
textStyle: { fontSizePt: 12, typeface: "Arial", color: "accent2" },
manualLayout: { x: 0.2, y: 0.3 },
fill: "#FFFFFF",
line: { fill: "accent2", width: 1 },
},
});
trendline.apply({ forecastForward: null });
trendlines.deleteAt(0);
```
### Replace Chart Data
```ts
chart.setData("A1:C8");
chart.setData("'Source data'!A1:C8");
chart.setData(["'Source data'!A1:A8", "D1:D8", "G1:G8"]);
```
| Chart | Source columns |
| --- | --- |
| Bar, line, area, pie | Categories, then one column per series |
| Scatter | X values, then one Y column per series |
| Bubble | X, Y, Size per series |
| Treemap or sunburst | Outer-to-inner category levels, then values |
| Box and whisker or histogram | One numeric column per sample series |
### Empty Cells
```ts
chart.displayBlanksAs = "gap";
chart.displayBlanksAs = "zero";
chart.displayBlanksAs = "span";
chart.displayBlanksAs = null;
chart.displayBlanksAsOptions;
```
### Edit One Series Binding
```ts
const series = chart.series.getItemAt(0);
series.valuesSource = "'Source data'!D2:D8";
series.categoriesSource = "A2:A8";
series.xValuesSource = "B2:B8";
// Bubble charts:
series.bubbleSizesSource = "C2:C8";
// Treemap and sunburst charts:
series.categoryPathsSource = "A2:B8";
```
### Edit An Axis
```ts
const axes = chart.getAxisTargets(); // { axisId: number, axis: "x" | "y" }[]
const axisId = axes[0].axisId;
const axis = chart.getAxisById(axisId);
chart.applyAxis(axisId, {
min: 0,
max: 100,
title: { text: "Value", textStyle: { bold: true } },
});
```
### Scoped Data Labels
```ts
const target = { scope: "point", seriesIndex: 0, pointIndex: 1 } as const;
const targetExists = chart.hasDataLabelTarget(target);
const labels = chart.getDataLabels(target);
chart.applyDataLabels(target, { textStyle: { bold: true }, separator: " / " });
chart.applyDataLabels(target, { showValue: false });
chart.applyDataLabels(target, { showValue: null }); // Restore the parent flag.
chart.applyDataLabels(target, null); // Remove the entire point override.
chart.applyDataLabels({ scope: "series", seriesIndex: 0 }, {
showValue: true, numberFormatCode: "0.00",
});
chart.applyDataLabels({ scope: "chart" }, { position: "outEnd" });
```
### Series Markers And Bar Spacing
```ts
chart.applySeriesStyle(0, {
marker: { symbol: "diamond", size: 8, fill: "#156082" },
});
chart.applySeriesStyle(0, { marker: { size: 12 } });
chart.applySeriesStyle(0, { stroke: { style: "dashed", compound: "double" } });
chart.applySeriesStyle(0, { stroke: { width: 3 } });
chart.format.apply({ barOptions: { gapWidth: 150, overlap: 0 } });
```
## Chart To Image
```ts
const result = await workbook.chartToImage(0, chart.id);
```
## Images
```ts
const image = sheet.images.add({
blob: imageBytes,
contentType: "image/png",
anchor: {
from: { row: 1, col: 2 },
extent: { widthPx: 240, heightPx: 160 },
},
});
image.id;
image.bytes;
image.contentType;
image.prompt;
image.uri;
```
## Shapes
```ts
const shape = sheet.shapes.add({
geometry: "rect",
anchor: {
from: { row: 2, col: 3 },
extent: { widthPx: 240, heightPx: 80 },
},
fill: "#f8fafc",
line: { fill: "#334155", width: 1 },
});
shape.text = "Label";
shape.geometry = "roundRect";
shape.geometry; // "roundRect"
shape.borderRadius = 16;
shape.borderRadius;
shape.borderRadiusApplies;
```
## Sparklines
```ts
const group = sheet.sparklineGroups.add({
targetRange: sheet.getRange("D2:D10"),
sourceData: sheet.getRange("B2:C10"),
type: "line",
});
group.apply({
sourceData: "'Source data'!B2:C12",
locationRange: "D2:D12",
type: "line",
lineWeight: 2,
dateAxisRange: "'Source data'!B1:C1",
displayHidden: false,
axis: { manualMin: 0, manualMax: 100 },
});
group.apply({ axis: { manualMin: undefined, manualMax: undefined } });
group.apply({ dateAxisRange: undefined }); // Restore evenly spaced samples.
group.sourceAddress;
group.dateAxisAddress;
group.dateAxisFormula;
group.uid;
```
## Auto Layout
```ts
sheet.autoLayoutDrawings(sheet.charts.items, {
direction: "vertical",
frame: { startCell: "E2", width: 800, height: 1200 },
gap: 16,
padding: 24,
});
```
## Cookbook
```ts
sheet.getRange("A1:B4").values = [
["Name", "Value"],
["A", 3],
["B", 5],
["C", 8],
];
sheet.charts.add("bar", {
from: { row: 1, col: 4 },
extent: { widthPx: 420, heightPx: 260 },
});
```
@@ -0,0 +1,78 @@
# Comments, Notes, And Names
Workbook comments, notes, and names are root-level facades. Sheet-scoped names
are available from `worksheet.names`.
## Comments
```ts
workbook.comments.setSelf({
displayName: "Reviewer",
initials: "RV",
});
const thread = workbook.comments.addThread(
{ cell: sheet.getRange("B2") },
"Review this cell",
);
thread.addReply("Updated.");
thread.resolve();
thread.reopen();
```
Threads appear in `workbook.inspect({ kind: "thread" })` and resolve from
`th/...` anchors.
## Notes
```ts
workbook.notes;
```
Notes serialize through `workbook.toProto()` and participate in recorded
workbook state.
## Workbook-Scoped Names
```ts
workbook.names.addRange("SalesRange", "Data!$A$1:$A$3", {
description: "Sales data",
});
const namedRange = workbook.names.getItem("SalesRange");
const range = namedRange.getRange();
namedRange.delete();
```
## Functions
```ts
workbook.names.addFunction("AddTax", {
lambda: "=LAMBDA(amount, amount * 1.1)",
description: "Add tax",
});
```
## Sheet-Scoped Names
```ts
sheet.names.addRange("LocalRange", "Sheet1!$A$1:$A$10");
```
## Alias
```ts
workbook.definedNames === workbook.names;
```
## Cookbook
```ts
const data = workbook.worksheets.add("Data");
data.getRange("A1:A3").values = [[1], [2], [3]];
workbook.names.add("SalesRange", data.getRange("A1:A3"));
workbook.comments.setSelf({ displayName: "Reviewer", initials: "RV" });
workbook.comments.addThread({ cell: data.getRange("A1") }, "Check value.");
```
@@ -0,0 +1,286 @@
# Formatting, Validation, And Theme
Use range formatting for cell style, worksheet collections for validation and
conditional formatting, and `workbook.colorScheme` for workbook theme colors.
## Range Format
```ts
range.format = {
fill: "#f8fafc",
font: {
name: "Aptos",
bold: true,
underline: "single",
color: "#0f172a",
size: 11,
},
borders: {
bottom: { style: "thin", color: "#94a3b8" },
},
numberFormat: "$#,##0.00",
horizontalAlignment: "center",
verticalAlignment: "middle",
wrapText: true,
rowHeightPx: 28,
columnWidthPx: 120,
};
```
### Cell fills
```ts
range.format.fill = {
type: "gradient",
angleDeg: 45,
offsetScale: 100000,
stops: [
{ offset: 0, color: "accent1" },
{ offset: 100000, color: "#ffffff" },
],
};
range.format.fill = {
type: "solid",
color: "#ffffff",
pattern: { type: "lightGrid", color: "#64748b" },
};
```
### Reading mixed formatting
```ts
const summary = range.format.getSummary();
if (summary.font.bold.state === "uniform") {
console.log(summary.font.bold.value);
}
range.format = { font: { bold: true } };
```
## Number Format
```ts
range.setNumberFormat("0.0%");
```
## Conditional Formatting
```ts
sheet.getRange("B2:B10").conditionalFormats.add("cellIs", {
operator: "greaterThan",
formula: 10,
format: {
fill: "#dcfce7",
font: { bold: true, color: "#166534" },
},
});
```
### Add and edit rules
```ts
const rule = sheet.conditionalFormattings.add({
range: "C2:C20",
rule: {
type: "cellIs",
operator: "greaterThan",
formula: "=$B2",
format: { font: { bold: true, underline: "single" }, numberFormat: "0.0%" },
},
stopIfTrue: true,
});
rule.assign({ ranges: ["C2:C20", "E2:E20"] });
rule.assign({ stopIfTrue: false });
const sameRule = sheet.conditionalFormattings.getItem(rule.id);
const matchingRules = sheet.conditionalFormattings.getIntersecting("C5");
rule.moveBefore(null); // Last priority.
```
### Edit rule formatting
```ts
rule.assign({
formatPatch: {
font: { bold: false, color: null }, // Reset the font color override.
border: { bottom: { style: "double" } },
numberFormat: "0.00%",
},
});
rule.assign({ ranges: ["E4:E20"], formatPatch: { font: { italic: true } } });
```
### Text predicates
```ts
const textRule = sheet.conditionalFormattings.add({
range: "A2:A20",
rule: {
type: "containsText",
text: "ready",
formula: '=AND(ISNUMBER(SEARCH("ready",A2)),B2>0)',
format: { fill: "accent2" },
},
});
textRule.assign({
predicatePatch: { type: "containsText", text: "approved" },
formatPatch: { font: { bold: true } },
ranges: ["C4:C22"],
});
textRule.assign({
predicatePatch: { type: "containsText", formula: null },
});
```
### Date-period formula overrides
```ts
const dates = sheet.conditionalFormattings.add({
range: "B2:B20",
rule: {
type: "timePeriod",
timePeriod: "last7Days",
formula: "=AND(B2>=TODAY()-7,B2<=TODAY())",
format: { fill: "accent2" },
},
});
const dateConfig = dates.config;
if (dateConfig.supported && dateConfig.rule.type === "timePeriod") {
dates.assign({ rule: { ...dateConfig.rule, formula: "=B2=TODAY()" } });
dates.assign({ rule: { ...dateConfig.rule, formula: undefined } });
}
```
### Data bars
```ts
const bars = sheet.conditionalFormattings.add({
range: "B2:B20",
rule: {
type: "dataBar",
color: "accent1",
gradient: false,
showValue: true,
minLength: 0,
maxLength: 100,
direction: "leftToRight", // "context" | "leftToRight" | "rightToLeft"
axisPosition: "automatic", // "automatic" | "middle" | "none"
border: true,
borderColor: "accent1",
negativeBarColorSameAsPositive: false,
negativeFillColor: "accent2",
negativeBarBorderColorSameAsPositive: false,
negativeBorderColor: "accent2",
axisColor: "text1",
thresholds: [{ type: "autoMin" }, { type: "autoMax" }],
},
});
const snapshot = bars.config;
if (snapshot.supported && snapshot.rule.type === "dataBar") {
bars.assign({ rule: { ...snapshot.rule, showValue: false } });
}
```
### Icon sets
```ts
sheet.conditionalFormattings.add({
range: "C2:C20",
rule: {
type: "iconSet",
iconSet: "3Arrows",
thresholds: [
{ type: "num", value: 0 },
{ type: "formula", value: "=$E$2", gte: false },
{ type: "formula", value: "=$E$3", gte: true },
],
},
});
```
### Clear and delete rules
```ts
sheet.conditionalFormattings.clear("E5:E6");
rule.delete();
```
## Data Validation
```ts
sheet.getRange("A2:A10").dataValidation = {
list: {
source: ["Open", "Closed"],
inCellDropDown: true,
},
allowBlank: true,
};
```
The range setter accepts list assignments or validation config
objects.
```ts
sheet.getRange("B2:B20").dataValidation = {
rule: { type: "whole", operator: "between", formula1: 0, formula2: 100 },
ignoreBlanks: true,
prompt: { show: true, title: "Score", message: "Enter 0–100." },
errorAlert: {
show: true,
style: "warning",
message: "Outside the expected range.",
},
};
sheet.getRange("B5").dataValidation.clear();
```
### Check cell values
```ts
const cell = sheet.getRange("B2");
const check = workbook.checkCellValue(sheet.name, "B2", 150);
const result = cell.setValueChecked(150);
if (
!result.applied &&
!result.validation.valid &&
result.validation.style !== "stop"
) {
// After the user confirms the warning/information message:
cell.setValueChecked(150, { acceptWarning: true });
}
```
## Freeze Panes
```ts
sheet.freezePanes.freezeRows(1);
sheet.freezePanes.freezeColumns(1);
sheet.freezePanes.unfreeze();
```
## Theme
```ts
const current = workbook.colorScheme;
console.log(current.name, current.themeColors.accent1);
workbook.colorScheme = {
name: "Workbook Theme",
themeColors: {
accent1: "#2563eb",
accent2: "#0f766e",
bg1: "#ffffff",
tx1: "#0f172a",
},
};
```
## Cookbook
```ts
const header = sheet.getRange("A1:C1");
header.format = {
fill: "#0f172a",
font: { bold: true, color: "#ffffff" },
horizontalAlignment: "center",
};
sheet.freezePanes.freezeRows(1);
```
@@ -0,0 +1,74 @@
# Formulas
Workbook formulas are stored on ranges and evaluated by `workbook.recalculate()`.
## Assign Formulas
```ts
sheet.getRange("A1:B2").values = [
[2, 3],
[5, 7],
];
sheet.getRange("C1:C2").formulas = [["=A1+B1"], ["=A2+B2"]];
workbook.recalculate();
```
Strings starting with `=` assigned through `values` are treated as formulas.
Use a leading apostrophe for literal strings:
```ts
sheet.getRange("C1").values = [["=SUM(A1:B1)"]];
sheet.getRange("D1").values = [["'=SUM(A1:B1)"]];
```
## Dynamic Arrays And Spill
```ts
sheet.getRange("E1").formulas = [["=SEQUENCE(3, 2)"]];
workbook.recalculate();
```
Spill projection cells are not directly editable formula anchors.
## Trace
```ts
const trace = workbook.trace("Sheet1!C1");
```
`trace` recalculates first and returns a dependency tree for the target cell or
`null` for an invalid reference.
## Formula Usage Stats
```ts
const stats = workbook.collectFormulaUsageStats();
```
## Names
```ts
workbook.names.addRange("SalesRange", "Data!$A$1:$A$3", {
description: "Sales data",
});
workbook.names.addFunction("AddTax", {
lambda: "=LAMBDA(amount, amount * 1.1)",
description: "Add tax",
});
sheet.names.addRange("LocalRange", "Sheet1!$A$1:$A$10");
```
## Cookbook
```ts
const workbook = Workbook.create();
const sheet = workbook.worksheets.add("Calc");
sheet.getRange("A1:A3").values = [[1], [2], [3]];
sheet.getRange("B1").formulas = [["=SUM(A1:A3)"]];
workbook.recalculate();
const trace = workbook.trace("Calc!B1");
```
@@ -0,0 +1,168 @@
# Import, Export, HTML, Images, And Google Sheets
Workbook import/export helpers cover CSV, Markdown, HTML copy/paste,
image/chart conversion, rendering, and Google Sheets adapter flows.
## CSV
```ts
const workbook = await Workbook.fromCSV(csv, {
sheetName: "Data",
});
const { sheet, range } = await workbook.fromCSV(csv, {
sheetName: "Imported",
});
```
## Markdown Table
```ts
const workbook = await Workbook.fromMarkdown(markdown, {
sheetName: "Data",
format: true,
});
```
Markdown import expects a Markdown table. With `format: true`, the imported
range is formatted as a worksheet table and columns are autofit.
## HTML
```ts
const html = source.toHTML(0, "A1:B2");
const withFormulas = source.toHTML(0, "A1:B2", { formulas: true });
const result = target.fromHTML(0, html, "C3");
const filled = target.fromHTML(0, html, "B2:C4");
```
`sheetIndex` is zero-based. The optional range uses A1 syntax.
## Image Import
```ts
const result = workbook.fromImage(
0,
{ bytes: imageBytes, contentType: "image/png" },
"A1:D10",
);
```
### Worksheet Images
```ts
const sheet = workbook.worksheets.getItem("Data");
sheet.images.add({
svg: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10" /></svg>',
anchor: {
from: { row: 0, col: 4 },
extent: { widthPx: 48, heightPx: 48 },
},
});
```
## Chart To Image
```ts
const result = await workbook.chartToImage(0, chart.id);
```
## Render And Export
```ts
const renderBlob = await workbook.render({
sheet: "Data",
range: "A1:C10",
format: "png",
scale: 2,
});
const exportBlob = await workbook.export({
sheetName: "Data",
range: "A1:C10",
format: "png",
scale: 2,
headers: true,
});
const layoutBlob = await workbook.export({
sheetName: "Data",
range: "A1:C10",
format: "layout",
});
const allSheetsPdf = await workbook.export({ format: "pdf" });
const uniformSheetsPdf = await workbook.export({
format: "pdf",
pageSizing: "uniform",
headers: true,
});
const oneSheetPdf = await workbook.export({
sheetName: "Data",
format: "pdf",
scale: 2,
});
const xlsxBlob = await workbook.export({
format: "xlsx",
fileName: "report.xlsx",
});
```
`format: "pdf"` exports all worksheets in workbook order. `sheet`, `sheetName`,
or `sheetIndex` selects one worksheet. PDF `pageSizing` accepts `"per-sheet"`
(default) or `"uniform"`.
`format: "layout"` exports sheet/range geometry, cell frames, styles, merged
ranges, validations, defined names, and drawing anchors. It supports sheet
selection, `range`, and `autoCrop`. `center`, `width`, and `height` apply to
preview and PDF exports, not layout.
## Export Inline Types
```ts
type WorkbookExportFormat = "png" | "jpeg" | "layout" | "xlsx" | "pdf";
type WorkbookExportOptions = {
fileName?: string;
sheet?: Worksheet | string | number;
sheetName?: string;
sheetIndex?: number;
range?: string;
center?: string;
width?: number;
height?: number;
scale?: number;
autoCrop?: "all" | "charts";
headers?: boolean;
format?: WorkbookExportFormat;
quality?: number;
pageSizing?: "per-sheet" | "uniform";
};
```
## Google Sheets
```ts
const workbook = await Workbook.fromGoogleSheets(config);
workbook.configureGoogleSheets(config);
const { patch } = workbook.record(() => {
workbook.worksheets.getItem("Data").getRange("A1").values = [["Updated"]];
});
await workbook.apply(patch, { target: "googleSheets" });
```
## Cookbook
```ts
const workbook = await Workbook.fromCSV(csv, { sheetName: "Data" });
const preview = await workbook.export({
sheetName: "Data",
range: "A1:D20",
format: "png",
scale: 2,
});
const proto = workbook.toProto();
```
@@ -0,0 +1,152 @@
# Inspect and Help
`workbook.inspect({ select, include })` queries a semantic workbook tree with RFC 9535 JSONPath. The [JSON Schema](inspect.schema.json) describes the nodes and value semantics.
## Navigate before reading cells
```ts
const overview = await workbook.inspect({
select: "$.sheets[*]",
include: ["name", "range", "tables.name", "tables.range", "tables.columns.name"],
});
console.log(overview.records);
const statistics = await workbook.inspect({
select: "$.sheets[?(@.name == 'Data')].columns[?(@.letter == 'B')].statistics",
include: ["numericCount", "min", "max", "sum", "average", "errorCount"],
});
console.log(statistics.records);
```
The tree contains `sheets` and workbook-scoped `definedNames`. Sheets contain native `tables`, `charts`, `drawings`, `pivotTables`, `sparklines`, `slicers`, what-if `dataTables`, `threads`, classic `notes`, `dataValidations`, `conditionalFormats`, `mergedRanges`, `freezePanes`, and layout metadata. Select the fields needed for the decision. Objects retain public names, drawing IDs, or fully qualified A1 addresses for subsequent edits.
`regions` describes inferred data blocks separately from native tables. Each region bounds cells connected horizontally or vertically through nonblank values or formulas. Rectangles can contain blanks and can overlap; their statistics describe the full rectangle. Region column names are copied from text in the first row, without inferring a formal header or changing the workbook.
```ts
const regions = await workbook.inspect({
select: "$.sheets[*].regions[*]",
include: ["sheet", "range", "rowCount", "columnCount", "columns.name"],
});
const sources = await workbook.inspect({
select: "$.sheets[*].charts[*]",
include: ["sheet", "id", "title", "type", "series.name", "series.formula", "series.categoryFormula"],
});
```
Statistics use finite computed numbers. Numeric-looking strings, dates, booleans, blanks, and errors are counted separately. `min`, `max`, and `average` are `null` without numeric values; `sum` is zero. An overflowing sum is `null`. Native table column statistics exclude headers and totals. Sheet and inferred-region column statistics cover their reported ranges.
## Search content, formulas, and appearance
```ts
const matches = await workbook.inspect({
select: "$.sheets[*].cells[?search(@.text, 'Revenue')]",
include: ["sheet", "address", "text"],
});
const errors = await workbook.inspect({
select: "$.sheets[*].cells[?(@.formula && @.valueType == 'error')]",
include: ["sheet", "address", "formula", "error"],
});
const formatting = await workbook.inspect({
select: "$.sheets[?(@.name == 'Data')].cells[?(@.row <= 10 && @.column <= 4)]",
include: ["address", "value", "text", "computedStyle.numberFormat", "computedStyle.fillColor"],
});
```
Cells are sparse, sorted by row and column, and include materialized styled blanks. Untouched blank positions are absent; whole-row and whole-column layout spans are represented separately. Cell row/column numbers are one-based; sheet index is zero-based. `value` is JSON-safe, dates are ISO timestamps, and `valueType` distinguishes dates and errors from strings. Formulas include `=`. Follow the workbook calculation lifecycle: recalculate after formula/input edits before querying current computed results.
`text` is displayed text. `computedStyle` follows the renderer, including inheritance, table/pivot formatting, theme colors, number-format colors, and supported conditional effects. Fields contain format codes, readable alignments, point font sizes, and resolved colors. Conditional rule definitions are separately available, including visual effects such as data bars and icon sets.
Mixed rich text exposes resolved `runs`; `computedStyle.font` describes the cell default when runs differ. Cells also expose their `links`, applicable `validation`, and containing `mergedRange`. Sheet `layout` reports authored/default dimensions and hidden spans, without expanding entire rows or columns into blank cell records.
Filters run before exact projection. `include` is an array of fields on selected nodes; dotted paths project nested objects and arrays. JSONPath slices, unions, recursive traversal, and standard `match()`/`search()` functions work without another inspection language.
`match()` and `search()` are case-sensitive. For example, `search(@.text, '[Rr]evenue')` matches both `Revenue` and `revenue`. A legacy case-insensitive regex needs an explicit equivalent when moving to JSONPath.
## Complete results and sessions
```ts
const result = await workbook.inspect({
select: "$.sheets[*].cells[?(@.formula)]",
include: ["sheet", "address"],
fileName: "formula-addresses.ndjson",
});
console.log(result.recordCount);
```
Files contain every selected record, with no hidden preview truncation. Narrow `select` and `include` to control size. `records` and `ndjson` remain available programmatically; ordinary result serialization returns count and output metadata. Return `result.records` explicitly from a session callback for a small immediate answer. Completed files are listed separately by the session runner.
```ts
type WorkbookInspectQueryOptions = {
select: string;
include?: readonly string[];
fileName?: string;
};
```
The previous `kind`/`searchTerm` API remains a separate overload. JSONPath requests use `select`, `include`, and `fileName` only.
## Find cells and API guidance
```ts
const matches = workbook.findCells({
searchTerm: "East", sheetId: "Data",
options: { maxResults: 10, matchFormulas: true },
});
```
Result matches include sheet, address, value/formula match metadata, and total
count.
## Help
```ts
const help = workbook.help("*", {
search: "colorScheme|worksheet.charts.add",
include: ["index", "examples", "notes"],
maxChars: 12000,
});
console.log(help.ndjson);
```
Common queries:
```text
*, workbook.colorScheme, worksheet.charts.add, formulas, enum.ChartType
```
## Navigate inspection results
Inspection IDs use each object's public navigation API. Select worksheets with `workbook.worksheets.getItem(id)`, cells with `sheet.getRange(address)`, and inferred regions with `sheet.getRange(range)`. Native table and slicer IDs are names for their sheet collections' `getItem(id)` methods; pivot IDs work with `workbook.pivotTables.getItem(id)`. Drawings retain their collection IDs. Include `sheet` when selecting objects across sheets.
Returned chart (`ch/<id>`) and thread (`th/<id>`) anchors work directly with `workbook.resolve`. Legacy worksheet anchors (`ws/<id>`) also continue to work; an inspection sheet's `id` is its public name, rather than a `ws/` anchor.
## Create/Edit Loop
```ts
const before = await workbook.inspect({
select: "$.sheets[?(@.name == 'Data')].cells[?(@.row == 2 && @.column == 2)]",
include: ["address", "value", "formula"],
});
const sheet = workbook.worksheets.getItem("Data");
sheet.getRange("B2").values = [["Closed"]];
workbook.recalculate();
const after = await workbook.inspect({
select: "$.sheets[?(@.name == 'Data')].cells[?(@.row == 2 && @.column == 2)]",
include: ["address", "value", "formula"],
});
```
## Inline Types
```ts
type WorkbookHelpOptions = {
include?: string[] | string;
search?: string;
maxChars?: number;
};
```
@@ -0,0 +1,122 @@
# Pivot Tables
## Create and Summarize
```ts
const data = workbook.worksheets.add("Data");
const output = workbook.worksheets.add("Summary");
data.getRange("A1:C5").values = [
["Region", "Product", "Sales"],
["East", "A", 10],
["East", "B", 20],
["West", "A", 30],
["West", "B", 40],
];
const pivot = output.pivotTables.add(
"SalesSummary",
data.getRange("A1:C5"),
output.getRange("A1"),
);
pivot.rowHierarchies.add(pivot.hierarchies.getItem("Region"));
pivot.columnHierarchies.add(pivot.hierarchies.getItem("Product"));
const sales = pivot.dataHierarchies.add(pivot.hierarchies.getItem("Sales"));
sales.summarizeBy = "Sum";
sales.name = "Revenue";
sales.numberFormat = "#,##0.00";
pivot.layout.layoutType = "Tabular";
sales.field.name;
pivot.layout.getDataBodyRange().values;
```
## Show Values As
```ts
sales.showAs = { calculation: "PercentOfGrandTotal" };
sales.numberFormat = "0.0%";
const region = pivot.hierarchies.getItem("Region").fields.getItem("Region");
sales.showAs = {
calculation: "DifferenceFrom",
baseField: region,
baseItem: region.items.getItem("East"),
};
```
```ts
sales.showAs = { calculation: "RunningTotal", baseField: region };
sales.showAs = { calculation: "PercentRunningTotal", baseField: region };
sales.showAs = { calculation: "RankDecending", baseField: region };
sales.showAs = { calculation: "PercentOfParentRowTotal" };
sales.showAs = { calculation: "Index" };
```
## Layout, Subtotals, and Sorting
```ts
pivot.layout.layoutType = "Tabular";
pivot.layout.showRowGrandTotals = false;
pivot.layout.showColumnGrandTotals = false;
pivot.layout.subtotalLocation = "AtBottom"; // "AtTop" | "AtBottom" | "Off"
pivot.layout.repeatAllItemLabels(true);
pivot.layout.displayBlankLineAfterEachItem(false);
pivot.styleName = "PivotStyleMedium2";
pivot.layout.hideValuesRow = true;
region.subtotals = { automatic: false };
region.subtotals = { sum: true, average: true, count: true };
region.sortByLabels("Ascending");
region.sortByValues("Descending", sales);
```
```ts
const product = pivot.hierarchies.getItem("Product").fields.getItem("Product");
region.sortByValues("Descending", sales, [product.items.getItem("A")]);
```
## Filter Fields
```ts
region.applyFilter({ manualFilter: { selectedItems: ["East"] } });
region.applyFilter({ labelFilter: { condition: "BeginsWith", substring: "E" } });
region.applyFilter({
valueFilter: { condition: "GreaterThan", comparator: 25, value: "Revenue" },
});
region.clearAllFilters();
```
```ts
region.getFilters();
region.isFiltered();
region.isFiltered("Value");
region.clearFilter("Value");
region.clearAllFilters();
```
## Edit Hierarchies and Items
```ts
const hierarchy = pivot.rowHierarchies.getItem("Region");
hierarchy.name = "Area";
hierarchy.position = 0;
sales.position = 0;
const item = region.items.getItem("East");
item.name = "Atlantic";
item.isExpanded = false;
item.visible = false;
```
## Read and Delete
```ts
pivot.refresh();
const existing = workbook.pivotTables.getItemOrNullObject("SalesSummary");
if (existing !== null) {
existing.dataHierarchies.items;
existing.layout.getDataBodyRange();
}
pivot.rowHierarchies.remove(hierarchy);
pivot.dataHierarchies.remove(sales);
workbook.pivotTables.getItem("SalesSummary").delete();
```
@@ -0,0 +1,150 @@
# Ranges
Ranges read and write cell values, formulas, formatting, validation,
conditional formats, sparklines, merges, fills, and copies.
## Addressing
```ts
const range = sheet.getRange("A1:B2");
const byIndexes = sheet.getRangeByIndexes(0, 0, 2, 2);
const cell = sheet.getCell(0, 0);
range.address;
range.getAddress();
range.rowIndex;
range.columnIndex;
range.rowCount;
range.columnCount;
```
## Values
```ts
sheet.getRange("A1:B2").values = [
[1, 2],
[3, 4],
];
sheet.getRange("B1:I1").values = [1, 2, 3, 4, 5, 6, 7, 8];
sheet.getRange("A2:A5").values = ["a", "b", "c", "d"];
```
Single-cell ranges can spill larger matrices:
```ts
sheet.getRange("N9").values = [[1, 2, 3]];
sheet.getRange("B2").values = [[1], [2], [3]];
```
## Formulas
```ts
sheet.getRange("C1").values = [["=SUM(A1:B1)"]];
sheet.getRange("D1").values = [["'=SUM(A1:B1)"]];
sheet.getRange("C1:C2").formulas = [["=A1+B1"], ["=A2+B2"]];
sheet.getRange("B3:E3").formulas = ["=1+1", "=2+2", "=3+3", "=4+4"];
sheet.getRange("G2:G5").formulas = ["=10", "=11", "=12", "=13"];
```
## Write
```ts
sheet.getRange("A1").write([
["Name", "Value"],
["A", 1],
]);
sheet.getRange("C1").write({ formulas: [["=SUM(B2:B10)"]] });
sheet.getRange("E1").write({ values: [["Literal"]] }, { overwrite: "error" });
```
## Format
```ts
range.format = {
fill: "#f8fafc",
font: { bold: true, color: "#0f172a" },
numberFormat: "$#,##0.00",
horizontalAlignment: "center",
verticalAlignment: "middle",
wrapText: true,
rowHeightPx: 28,
columnWidthPx: 120,
};
range.setNumberFormat("0.0%");
```
## Navigation
```ts
range.getCell(0, 1);
range.getRow(0);
range.getColumn(1);
range.getRange("A1");
range.getRangeByIndexes(0, 0, 1, 1);
range.getOffsetRange(1, 0);
range.getResizedRange(2, 3);
range.getResizeRange(10, 4);
range.offset(1, 0);
range.resize(10, 4);
range.getCurrentRegion();
```
## Clear, Merge, Fill, Copy
```ts
range.clear({ applyTo: "contents" });
range.clear({ applyTo: "formats" });
range.clear({ applyTo: "all" });
range.merge();
range.unmerge();
range.fillDown();
range.fillRight();
range.fillFrom(sourceRange);
range.copyFrom(sourceRange);
range.copyTo(targetRange);
range.copyFrom(sourceRange, "values");
range.copyTo(targetRange, "formulas");
```
## Inline Types
```ts
type CellValue = string | number | boolean | Date | null;
type RangeWriteOptions = {
clear?: "contents" | "formats" | "all";
overwrite?: "allow" | "error";
resize?: "auto" | "none";
};
type RangeWritePayload =
| CellValue[][]
| CellValue[]
| null
| {
values?: CellValue[][] | CellValue[] | null;
formulas?: string[][] | string[];
formulasR1C1?: string[][] | string[];
};
```
## Cookbook
```ts
const data = sheet.getRange("A1:C4");
data.values = [
["Region", "Q1", "Q2"],
["North", 10, 12],
["South", 8, 9],
["Total", null, null],
];
sheet.getRange("B4:C4").formulas = [["=SUM(B2:B3)", "=SUM(C2:C3)"]];
data.format = { numberFormat: "General", wrapText: true };
```
@@ -0,0 +1,93 @@
# Tables
Worksheet tables are created from an existing range and can edit rows, headers,
data body ranges, names, style, and totals.
## Add Table
```ts
const sheet = workbook.worksheets.add("Inventory");
sheet.getRange("A1:C3").values = [
["SKU", "Color", "Stock"],
["100-001", "Black", 15],
["100-002", "Sage", 40],
];
const table = sheet.tables.add("A1:C3", true, "InventoryTable");
```
## Read
```ts
sheet.tables.items;
sheet.tables.getItem("InventoryTable");
sheet.tables.getItemAt(0);
sheet.tables.getItemById(table.id);
sheet.tables.getIntersecting(sheet.getRange("A1:C5"));
table.id;
table.name;
table.rowCount; // data rows, excluding headers and totals
table.columnCount;
table.columnNames;
table.address;
table.getRange();
table.getHeaderRowRange();
table.getDataRows();
```
## Configure and Resize
```ts
table.name = "InventoryTable";
table.style = "TableStyleMedium9";
table.showHeaders = true;
table.showFilterButton = true;
table.showTotals = false;
table.showBandedRows = true;
table.showBandedColumns = false;
table.highlightFirstColumn = false;
table.highlightLastColumn = false;
table.resize("A1:C8");
```
## Add Rows
```ts
table.rows.add(null, [["100-003", "Denim", 12]]);
```
## Headerless Table
```ts
sheet.getRange("A1:B3").values = [
["West", 12],
["East", 9],
["South", 15],
];
sheet.tables.add("A1:B3", false, "HeaderlessTable");
```
## Recorded Table Edit
```ts
const { patch } = workbook.record(() => {
const table = sheet.tables.add("A1:C3", true, "InventoryTable");
table.rows.add(null, [["100-003", "Denim", 12]]);
});
```
The recorded patch uses `table.add` followed by row/column/table operations for
subsequent edits.
## Cookbook
```ts
const table = sheet.tables.add("A1:D5", true, "DataTable");
table.rows.add(null, [["West", "Ava", 12, 14]]);
sheet.getRange(table.address).format = {
font: { name: "Aptos" },
wrapText: true,
};
```
@@ -0,0 +1,129 @@
# Workbook Facade
## Create And Load
```ts
const workbook = Workbook.create();
const [sheet1, sheet2] = workbook.worksheets.add(["Sheet1", "Sheet2"]);
const loaded = Workbook.load(proto);
const validated = Workbook.load(proto, { validate: true });
```
## Import
```ts
const fromCsv = await Workbook.fromCSV(csv, { sheetName: "Data" });
const fromMarkdown = await Workbook.fromMarkdown(markdown, {
sheetName: "Data",
format: true,
});
const { sheet, range } = await workbook.fromCSV(csv, { sheetName: "Data" });
```
## Root Collections
```ts
workbook.worksheets;
workbook.sheets; // alias
workbook.pivotTables;
workbook.slicers;
workbook.comments;
workbook.notes;
workbook.names;
workbook.definedNames; // alias
workbook.awareness;
```
## Theme
```ts
workbook.colorScheme = {
name: "Workbook Theme",
themeColors: {
accent1: "#2563eb",
bg1: "#ffffff",
tx1: "#0f172a",
},
};
const theme = workbook.theme;
```
## Recalculate And Trace
```ts
workbook.recalculate();
const trace = workbook.trace("Data!C2");
const stats = workbook.collectFormulaUsageStats();
```
## Inspect, Search, Help, Resolve
```ts
const snapshot = await workbook.inspect({ kind: "sheet,table,formula" });
const matches = workbook.findCells({
searchTerm: "East",
sheetId: "Revenue",
options: { maxResults: 10, matchFormulas: true },
});
const help = workbook.help("*", {
search: "colorScheme|worksheet.charts.add",
include: ["index", "examples", "notes"],
});
const target = workbook.resolve(anchorId);
```
## Record And Apply
```ts
const { result, patch, idMap, crdtUpdateV2 } = workbook.record(() => {
const sheet = workbook.worksheets.getItem("Data");
sheet.getRange("A1").values = [["Value"]];
return sheet;
});
const applied = workbook.apply(patch);
```
## CRDT
```ts
workbook.hydrateCrdtFromProto();
const ready = workbook.isCollaborativeStateReady();
const unsubscribe = workbook.onCrdtUpdateV2((update, origin) => {
send(update);
});
workbook.applyCrdtUpdateV2(remoteUpdate, { recalculate: true });
unsubscribe();
```
## Serialize
```ts
const proto = workbook.toProto();
```
## Utilities
```ts
workbook.utils.columnToLetter(1); // "A"
workbook.utils.letterToColumn("AA"); // 27
workbook.utils.toA1String(1, 1, 3, 2); // "A1:B3"
workbook.utils.fillRight([[1]], 3); // [[1, 1, 1]]
workbook.utils.fillDown([[1]], 3); // [[1], [1], [1]]
```
## Cookbook
```ts
const workbook = Workbook.create();
const sheet = workbook.worksheets.add("Data");
sheet.getRange("A1:B2").values = [
["Name", "Value"],
["A", 1],
];
const { patch } = workbook.record(() => {
sheet.getRange("B2").values = [[2]];
});
```
@@ -0,0 +1,122 @@
# Worksheets
`workbook.worksheets` and `workbook.sheets` expose the worksheet collection.
## Collection
```ts
const sheet = workbook.worksheets.add("Data");
workbook.worksheets.add("New data", { ifExists: "error" });
const existing = workbook.worksheets.getItem("Data");
const maybe = workbook.worksheets.getItemOrNullObject("Data");
const first = workbook.worksheets.getFirst();
const active = workbook.worksheets.getActiveWorksheet();
workbook.worksheets.setActiveWorksheet("Data");
const count = workbook.worksheets.getSheetCount();
const index = workbook.worksheets.getSheetIndex("Data");
const name = workbook.worksheets.getSheetNameByIndex(0);
const byIndex = workbook.worksheets.getItemAt(0);
```
## Worksheet Properties
```ts
sheet.name = "Renamed";
sheet.index = 0;
sheet.showGridLines = false;
sheet.tabColor = "#1F4E78";
sheet.freezePanes.freezeRows(1);
sheet.freezePanes.freezeColumns(1);
sheet.id;
sheet.sheetId;
sheet.tabColor;
sheet.defaultRowHeight;
sheet.defaultColWidth;
sheet.baseColWidth;
```
## Ranges
```ts
const range = sheet.getRange("A1:B2");
const byIndexes = sheet.getRangeByIndexes(0, 0, 2, 2);
const cell = sheet.getCell(0, 0);
const used = sheet.getUsedRange();
const usedValuesOnly = sheet.getUsedRange(true);
```
`getRange` accepts A1 strings only. Use zero-based row/column indexes with
`getRangeByIndexes` and `getCell`.
## Worksheet Collections
```ts
sheet.tables;
sheet.charts;
sheet.shapes;
sheet.images;
sheet.pivotTables;
sheet.slicers;
sheet.sparklineGroups;
sheet.conditionalFormattings;
sheet.dataValidations;
sheet.freezePanes;
sheet.names;
sheet.cells;
```
## Reset And Delete
```ts
sheet.reset({
clear: "used",
applyTo: "all",
deleteTables: true,
deleteCharts: true,
deleteDrawings: true,
deleteSparklines: true,
});
sheet.delete();
```
## Merge
```ts
sheet.mergeCells("A1:B2");
sheet.unmergeCells("A1:B2");
```
## Drawings
```ts
sheet.deleteAllDrawings();
sheet.autoLayoutDrawings(items, options);
```
## Inline Types
```ts
type WorksheetResetOptions = {
clear?: "used" | "none";
applyTo?: "contents" | "formats" | "all";
deleteTables?: boolean;
deleteCharts?: boolean;
deleteDrawings?: boolean;
deleteSparklines?: boolean;
};
```
## Cookbook
```ts
const sheet = workbook.worksheets.add("Data");
sheet.getRange("A1:B2").values = [
["Name", "Value"],
["A", 1],
];
sheet.mergeCells("D1:E1");
sheet.freezePanes.freezeRows(1);
```
@@ -0,0 +1,56 @@
# Sparklines
```js
const group = sheet.sparklineGroups.add({
type: "line",
targetRange: "E2:E4",
sourceData: "A2:C4",
seriesColor: "#2563EB",
markers: { high: true, low: true },
});
```
- Sparkline type is a string. Use the public options documented below. Do not set internal/proto enum values for empty-cell display or axis modes; if a required option is not documented for the selected runtime, follow the bounded discovery policy.
- Avoid `dateAxisRange` for XLSX output; it is not serialized. Keep automatic axis limits: `manualMin` / `manualMax` alone do not select custom limits in Excel.
- Sparkline Inline Type:
```
type SparklineConfig = {
type: "line" | "column" | "stacked";
targetRange: Range | string;
sourceData: Range | string;
lineWeight?: number;
displayHidden?: boolean;
seriesColor?: ColorConfig;
negativeColor?: ColorConfig;
axisColor?: ColorConfig;
markersColor?: ColorConfig;
firstMarkerColor?: ColorConfig;
lastMarkerColor?: ColorConfig;
highMarkerColor?: ColorConfig;
lowMarkerColor?: ColorConfig;
markers?: SparklineMarkersOptions;
axis?: SparklineAxisOptions;
};
type SparklineMarkersOptions = {
show?: boolean;
high?: boolean;
low?: boolean;
first?: boolean;
last?: boolean;
negative?: boolean;
};
type SparklineAxisOptions = {
showAxis?: boolean;
rightToLeft?: boolean;
};
```
- Range Alias: `const group = targetRange.sparklines.add(type, sourceRange, sparklineConfig);`
- Edit And Delete
```js
group.seriesColor = "#2563EB";
group.markers.high = true;
group.axis.showAxis = true;
sheet.sparklineGroups.delete(group);
sheet.sparklineGroups.deleteAll();
```
@@ -0,0 +1,97 @@
import fs from "node:fs/promises";
import { SpreadsheetFile, Workbook, ChartDataLabels } from "@oai/artifact-tool";
async function buildChartSuggestionWorkbook(outputDir: string): Promise<void> {
await fs.mkdir(outputDir, { recursive: true });
const workbook = Workbook.create();
const sheet = workbook.worksheets.add("Charts");
sheet.showGridLines = false;
sheet.getRange("A1:C5").values = [
["Month", "Revenue", "EBITDA"],
["Jan", 100000, 18000],
["Feb", 121000, 23000],
["Mar", 132000, 28000],
["Apr", 149000, 34000],
];
sheet.getRange("A1:C1").format = {
fill: "#0F766E",
font: { bold: true, color: "#FFFFFF" },
};
sheet.getRange("B2:C5").format.numberFormat = "$#,##0";
sheet.getRange("A:C").format.columnWidthPx = 96;
// Fast chart path: chart a continuous helper range. The helper range is
// formula-backed so edits to the source table update the chart.
sheet.getRange("F1:H1").values = [["Month", "Revenue", "EBITDA"]];
sheet.getRange("F2:H2").formulas = [["=A2", "=B2", "=C2"]];
sheet.getRange("F2:H5").fillDown();
const lineChart = sheet.charts.add("line", sheet.getRange("F1:H5"));
lineChart.setPosition("J1", "Q15");
lineChart.title = "Revenue and EBITDA Trend";
lineChart.titleTextStyle.fontSize = 12;
lineChart.hasLegend = true;
lineChart.xAxis = { axisType: "textAxis" };
lineChart.yAxis = { numberFormatCode: "$#,##0" };
const scatterPlot = sheet.charts.add("scatter", sheet.getRange("F1:H5"));
scatterPlot.setPosition("J1", "Q15");
scatterPlot.title = "Revenue and EBITDA Trend Scatter";
scatterPlot.titleTextStyle.fontSize = 12;
scatterPlot.hasLegend = true;
scatterPlot.xAxis = { axisType: "textAxis" };
scatterPlot.yAxis = { numberFormatCode: "$#,##0" };
scatterPlot.dataLabels = new ChartDataLabels({showValue: true, position: 'above' });
// Advanced path: manually define a single series by formula.
const barChart = sheet.charts.add("bar", {
title: "EBITDA by Month",
hasLegend: false,
});
const series = barChart.series.add("EBITDA");
series.categoryFormula = "'Charts'!$A$2:$A$5";
series.formula = "'Charts'!$C$2:$C$5";
series.fill = "#F472B6";
barChart.setPosition("J18", "Q32");
barChart.title = "EBITDA by Month";
barChart.titleTextStyle.fontSize = 12;
barChart.xAxis = { axisType: "textAxis", textStyle: { fontSize: 10} };
barChart.yAxis = { numberFormatCode: "$#,##0", textStyle: { fontSize: 10} };
barChart.xAxis.title.text = "EBITDA";
barChart.yAxis.title.text = "Month";
barChart.yAxis.min = 10_000;
barChart.yAxis.max = 40_000;
barChart.yAxis.majorUnit = 5;
// TODO @vicky set default title text to be size 12
// setData replaces the chart source range; use it when a chart exists before
// the final source range is known.
lineChart.setData(sheet.getRange("F1:H5"));
const preview = await workbook.render({
sheetName: "Charts",
autoCrop: "all",
scale: 1,
format: "png",
});
await fs.writeFile(
`${outputDir}/typescript_chart_suggestions.png`,
new Uint8Array(await preview.arrayBuffer()),
);
const xlsx = await SpreadsheetFile.exportXlsx(workbook);
await xlsx.save(`${outputDir}/typescript_chart_suggestions.xlsx`);
console.log(`Rendered ${outputDir}/typescript_chart_suggestions.png`);
console.log(`Saved ${outputDir}/typescript_chart_suggestions.xlsx`);
}
const outputDir = process.argv[2] ?? "output/chart_suggestions";
buildChartSuggestionWorkbook(outputDir).catch((error: unknown) => {
console.error(error);
process.exit(1);
});
@@ -0,0 +1,177 @@
import { Workbook } from "@oai/artifact-tool";
function clip(value: string, maxChars: number): string {
return value.length > maxChars ? `${value.slice(0, maxChars)}...` : value;
}
function summarizeTrace(
root: any,
options: { maxDepth?: number; maxNodes?: number; maxFormulaChars?: number } = {},
): string[] {
if (!root) return ["(no trace returned)"];
const maxDepth = options.maxDepth ?? 4;
const maxNodes = options.maxNodes ?? 30;
const maxFormulaChars = options.maxFormulaChars ?? 120;
const lines: string[] = [];
let nodeCount = 0;
let truncated = false;
function walk(node: any, depth: number): void {
if (nodeCount >= maxNodes) {
truncated = true;
return;
}
nodeCount += 1;
const indent = " ".repeat(depth);
const formula = node.formula
? ` formula=${clip(String(node.formula), maxFormulaChars)}`
: "";
const error = node.error ? ` error=${node.error}` : "";
lines.push(`${indent}${node.cell} value=${JSON.stringify(node.value)}${formula}${error}`);
const children = (node.params ?? []) as any[];
if (children.length === 0) return;
if (depth >= maxDepth) {
truncated = true;
lines.push(`${indent} ... ${children.length} precedent(s) not shown`);
return;
}
for (const child of children) {
walk(child, depth + 1);
}
}
walk(root, 0);
if (truncated) lines.push(`... trace summary capped at depth ${maxDepth}, ${maxNodes} nodes`);
return lines;
}
function findTraceNode(root: any, cell: string): any | null {
if (!root) return null;
if (root.cell === cell) return root;
for (const child of (root.params ?? []) as any[]) {
const found = findTraceNode(child, cell);
if (found) return found;
}
return null;
}
function formatNumber(value: unknown): string {
if (typeof value !== "number") return String(value);
if (value !== 0 && Math.abs(value) < 0.01) return Number(value.toPrecision(3)).toString();
return value.toLocaleString("en-US", { maximumFractionDigits: 2 });
}
function formatPercent(value: unknown): string {
return typeof value === "number" ? `${(value * 100).toFixed(1)}%` : String(value);
}
function explainRevenueCheck(trace: any): string {
const status = findTraceNode(trace, "Checks!F2")?.value;
const difference = findTraceNode(trace, "Checks!D2")?.value;
const actual = findTraceNode(trace, "Checks!B2")?.value;
const expected = findTraceNode(trace, "Checks!C2")?.value;
const tolerance = findTraceNode(trace, "Checks!E2")?.value;
const baseRevenue = findTraceNode(trace, "Inputs!B2")?.value;
const growthRate = findTraceNode(trace, "Inputs!B3")?.value;
const revenue2025 = findTraceNode(trace, "Model!B4")?.value;
return [
`Checks!F2 returns "${status}" because the absolute difference is within the tolerance.`,
`It compares Checks!D2 (${formatNumber(difference)}) against Checks!E2 (${formatNumber(tolerance)}).`,
`Checks!D2 is actual revenue minus expected revenue: Checks!B2 (${formatNumber(actual)}) - Checks!C2 (${formatNumber(expected)}).`,
`The actual value comes from Model!B5, which compounds Inputs!B2 (${formatNumber(baseRevenue)}) by the growth rate in Inputs!B3 (${formatPercent(growthRate)}) for two years: first to Model!B4 (${formatNumber(revenue2025)}), then to Model!B5 (${formatNumber(actual)}).`,
`Caveat: the tiny difference shown is floating-point rounding noise, not a business variance.`,
].join("\n");
}
async function main(): Promise<void> {
const workbook = Workbook.create();
const inputs = workbook.worksheets.add("Inputs");
const model = workbook.worksheets.add("Model");
const checks = workbook.worksheets.add("Checks");
inputs.getRange("A1:B4").values = [
["Metric", "Value"],
["Revenue 2024", 100],
["Growth Rate", 0.1],
["Expected Revenue 2026", 121],
];
model.getRange("A1:B5").values = [
["Metric", "Value"],
["Revenue 2024", null],
["Growth Rate", null],
["Revenue 2025", null],
["Revenue 2026", null],
];
model.getRange("B2:B5").formulas = [
["=Inputs!B2"],
["=Inputs!B3"],
["=B2*(1+B3)"],
["=B4*(1+B3)"],
];
checks.getRange("A1:F2").values = [
["Check", "Actual", "Expected", "Difference", "Tolerance", "Status"],
["Revenue 2026 ties to expected case", null, null, null, 0.001, null],
];
checks.getRange("B2:D2").formulas = [["=Model!B5", "=Inputs!B4", "=B2-C2"]];
checks.getRange("F2").formulas = [["=IF(ABS(D2)<=E2,\"OK\",\"CHECK\")"]];
workbook.recalculate();
const trace = workbook.trace("Checks!F2");
console.log("=== Formula trace for Checks!F2 ===");
console.log(
summarizeTrace(trace, {
maxDepth: 4,
maxNodes: 20,
}).join("\n"),
);
console.log("\n=== User-facing answer: How is Checks!F2 calculated? ===");
console.log(explainRevenueCheck(trace));
console.log("\n=== Exact formula help: XLOOKUP ===");
console.log(
workbook.help("fx.XLOOKUP", {
include: "index,examples,notes",
maxChars: 2500,
}).ndjson,
);
console.log("\n=== Formula category browse: financial ===");
console.log(
workbook.help("fx.*", {
search: "financial",
include: "index,examples",
maxChars: 2500,
}).ndjson,
);
console.log("\n=== Formula category browse: math-trig ===");
console.log(
workbook.help("fx.*", {
search: "math-trig",
include: "index,examples",
maxChars: 2500,
}).ndjson,
);
console.log("\n=== Semantic formula search: lookup with fallback ===");
console.log(
workbook.help("lookup value with fallback", {
search: "XLOOKUP|INDEX|MATCH|IFERROR",
include: "index,examples,notes",
maxChars: 3000,
}).ndjson,
);
}
main().catch((error: unknown) => {
console.error(error);
process.exit(1);
});
@@ -0,0 +1,113 @@
import * as fs from "node:fs/promises";
import * as path from "node:path";
import {
FileBlob,
SpreadsheetFile,
} from "../../../../oai_js_artifact_tool";
const DEFAULT_WORKBOOK_INPUTS = [
"/Users/vicky/code/openai/output/spreadsheet-atv/fitness-tracker-20260409",
];
type InspectResult = {
ndjson: string;
};
async function resolveWorkbookPath(inputPath: string): Promise<string> {
const expandedPath = inputPath.startsWith("~")
? path.join(process.env.HOME ?? "", inputPath.slice(1))
: inputPath;
const stats = await fs.stat(expandedPath);
if (stats.isFile()) {
return expandedPath;
}
if (stats.isDirectory()) {
const candidates = (await fs.readdir(expandedPath))
.filter((entry) => entry.endsWith(".xlsx"))
.sort();
if (candidates.length > 0) {
return path.join(expandedPath, candidates[0]);
}
throw new Error(`No .xlsx files found in directory: ${expandedPath}`);
}
throw new Error(`Workbook path is not a file or directory: ${expandedPath}`);
}
function printInspect(title: string, result: InspectResult): void {
console.log(`\n=== ${title} ===`);
if (result.ndjson) {
console.log(result.ndjson);
return;
}
console.log("(no rows returned)");
}
async function inspectWorkbook(workbookPath: string): Promise<void> {
const workbook = await SpreadsheetFile.importXlsx(await FileBlob.load(workbookPath));
const firstSheet = workbook.worksheets.getItemAt(0);
const firstSheetName = firstSheet.name;
console.log(`\n########## Inspecting ${workbookPath} ##########`);
console.log(`First worksheet: ${firstSheetName}`);
const summary = await workbook.inspect({
kind: "workbook,sheet,table",
maxChars: 6000,
tableMaxRows: 6,
tableMaxCols: 6,
tableMaxCellChars: 80,
});
printInspect("Workbook summary", summary);
const sheetsIndex = await workbook.inspect({
kind: "sheet",
include: "id,name",
});
printInspect("Sheets index", sheetsIndex);
const firstRegion = await workbook.inspect({
kind: "region",
sheetId: firstSheetName,
range: "A1:Z30",
maxChars: 2500,
tableMaxRows: 12,
tableMaxCols: 8,
tableMaxCellChars: 50,
});
printInspect(`First sheet region preview (${firstSheetName}!A1:Z30)`, firstRegion);
const formulas = await workbook.inspect({
kind: "formula",
sheetId: firstSheetName,
maxChars: 2000,
});
printInspect(`Formula snapshot (${firstSheetName})`, formulas);
const drawings = await workbook.inspect({
kind: "drawing",
sheetId: firstSheetName,
maxChars: 2000,
});
printInspect(`Drawing snapshot (${firstSheetName})`, drawings);
}
async function inspectExistingWorkbooks(inputPaths: string[]): Promise<void> {
for (const inputPath of inputPaths) {
const workbookPath = await resolveWorkbookPath(inputPath);
await inspectWorkbook(workbookPath);
}
}
async function main(): Promise<void> {
const inputPaths =
process.argv.slice(2).length > 0
? process.argv.slice(2)
: DEFAULT_WORKBOOK_INPUTS;
await inspectExistingWorkbooks(inputPaths);
}
main().catch((error: unknown) => {
console.error(error);
process.exit(1);
});
@@ -0,0 +1,146 @@
import fs from "node:fs/promises";
import { SpreadsheetFile, Workbook } from "@oai/artifact-tool";
/**
* Quick Start Examples
* This runnable TypeScript example mirrors:
* lib/agent/tools/artifact_tool_v2/skills/python/spreadsheets/examples/quick_start_example.py
*/
async function quickApiExample(): Promise<void> {
// Creating a workbook and adding sheets with data and basic formatting
const workbook = Workbook.create();
var sheet = workbook.worksheets.add("ExampleSheet");
sheet = workbook.worksheets.getItem("ExampleSheet");
sheet.getRange("A1:D4").values = [
["Name", "Personality Type", "Age", "Birthday"],
["John Doe", "Introvert", 30, new Date("1990-01-01T00:00:00Z")],
["Jane Smith", "Extrovert", 25, new Date("1995-02-15T00:00:00Z")],
["Jim Very Long Name", "Ambivert", 40, new Date("1980-03-20T00:00:00Z")],
];
sheet.getRange("E1").values = [["Score"]];
sheet.getRange("E2").formulas = [["=C2*10"]]; // score is 10 * age
sheet.getRange("E2:E4").fillDown();
const headerRange = sheet.getRange("A1:E1");
// Styling
const headerFormats = {
fill: "#0F766E",
font: { bold: true, color: "#FFFFFF" },
horizontalAlignment: "center",
verticalAlignment: "center",
rowHeight: 16,
};
headerRange.format = headerFormats;
headerRange.format.autofitColumns();
const dataRange = sheet.getRange("A2:D4");
dataRange.format.wrapText = true;
sheet.showGridLines = false;
// Format dates properly.
sheet.getRange("D2:D4").format.numberFormat = "MM/DD/YYYY";
// Conditional formatting
sheet.getRange("C2:C4").conditionalFormats.add("dataBar", {
color: "#704023",
gradient: true,
});
sheet.getRange("E2:E4").conditionalFormats.add("cellIs", {
operator: "greaterThan",
formula: 300,
format: { font: { color: "#B91C1C" } },
});
sheet.conditionalFormattings.add({
range: "B2:B4",
rule: {
type: "expression",
formula: '=B2="Introvert"',
format: { fill: "#FCA5A5" },
},
});
// Data validation: Since Personality Type is a dropdown category, add data validation.
sheet.getRange("B2:B4").dataValidation = {
rule: {
type: "list",
values: ["Introvert", "Extrovert", "Ambivert"],
// formula1: "CategoriesSheet!$A$2:$A$4", // Alternative: reference a tunable list
},
};
// Tables: Turn it into a table (for example purposes! Make sure table names are unique)
// NOTE: If hasHeaders=true, the range must include the header row.
const table = sheet.tables.add("A1:E4", true, "PeopleTable");
table.getHeaderRowRange();
// First column is still wide since we only auto-fit the first row. Expand it manually.
sheet.getRange("A1:A4").format.columnWidth = 20;
// Create a compact chart helper range that references the source table.
sheet.getRange("H1:I1").merge();
sheet.getRange("H1").values = [["Charts"]];
sheet.getRange("H1").format = headerFormats;
sheet.getRange("H3:I3").values = [["Person", "Score"]];
sheet.getRange("H4:I4").formulas = [["=A2", "=E2"]];
sheet.getRange("H4:I6").fillDown();
const chart = sheet.charts.add("bar", sheet.getRange("H3:I6"));
chart.title = "Person by Scores";
chart.hasLegend = true;
chart.displayBlanksAs = "zero";
chart.barOptions.direction = "column";
chart.barOptions.grouping = "clustered";
chart.setPosition("K2", "R16");
// Granular control over chart axes
chart.xAxis = {
axisType: "textAxis",
title: { text: "Person", textStyle: { fontSize: 13, bold: true } },
position: "bottom",
orientation: "minMax",
textStyle: { fontSize: 10 },
};
chart.yAxis = {
axisType: "textAxis",
title: { text: "Scores", textStyle: { fontSize: 13, bold: true } },
numberFormatCode: "0,000",
numberFormatSourceLinked: false,
};
// Sparklines: add to the right of table
const sparklinesHeader = sheet.getRange("F1");
sparklinesHeader.values = [["Sparklines"]];
sparklinesHeader.format = headerFormats;
sparklinesHeader.format.autofitColumns();
sheet.sparklines.add({
type: "column", // "line" | "column" | "stacked"
sourceData: sheet.getRange("E2:E4"),
targetRange: sheet.getRange("F2:F4"),
seriesColor: "#AAAAAA",
});
// Render
await fs.mkdir("output", { recursive: true });
const pngBlob = await workbook.render({
sheetName: "ExampleSheet",
autoCrop: "all",
scale: 1,
format: "png",
});
const pngBytes = new Uint8Array(await pngBlob.arrayBuffer());
await fs.writeFile("output/example_sheet.png", pngBytes);
console.log("Rendered first sheet to 'output/example_sheet.png'");
// Export
const out = "output/example_sheet.xlsx";
const xlsx = await SpreadsheetFile.exportXlsx(workbook);
await xlsx.save(out);
console.log(`Spreadsheet saved to ${out}`);
}
quickApiExample().catch((error: unknown) => {
console.error(error);
process.exit(1);
});
@@ -0,0 +1,32 @@
# Database Formulas
Database formulas aggregate rows from headered ranges using criteria ranges.
## Formula Pattern
```ts
const formulaBlock = sheet.getRange(outputRange).write({
formulas: formulaMatrix,
});
workbook.recalculate();
const results = formulaBlock.values;
```
## Common Shapes
```ts
const formulas = [
`=DSUM(${databaseRangeRef},${fieldRef},${criteriaRangeRef})`,
`=DCOUNT(${databaseRangeRef},${fieldRef},${criteriaRangeRef})`,
`=DCOUNTA(${databaseRangeRef},${fieldRef},${criteriaRangeRef})`,
`=DAVERAGE(${databaseRangeRef},${fieldRef},${criteriaRangeRef})`,
`=DMIN(${databaseRangeRef},${fieldRef},${criteriaRangeRef})`,
`=DMAX(${databaseRangeRef},${fieldRef},${criteriaRangeRef})`,
`=DSTDEV(${databaseRangeRef},${fieldRef},${criteriaRangeRef})`,
`=DVAR(${databaseRangeRef},${fieldRef},${criteriaRangeRef})`,
];
```
## Coverage
Supported families include database sum, count, average, min, max, product, standard deviation, variance, and single-value lookup.
@@ -0,0 +1,34 @@
# Date And Time Formulas
Date and time formulas create, parse, extract, and compare serial dates and times.
## Formula Pattern
```ts
const formulaBlock = sheet.getRange(outputRange).write({
formulas: formulaMatrix,
});
workbook.recalculate();
const results = formulaBlock.values;
```
## Common Shapes
```ts
const formulas = [
`=DATE(${yearRef},${monthRef},${dayRef})`,
`=TIME(${hourRef},${minuteRef},${secondRef})`,
`=DATEVALUE(${textRef})`,
`=TIMEVALUE(${textRef})`,
`=YEAR(${dateRef})`,
`=MONTH(${dateRef})`,
`=DAY(${dateRef})`,
`=WEEKDAY(${dateRef})`,
`=WORKDAY(${startDateRef},${daysRef})`,
`=NETWORKDAYS(${startDateRef},${endDateRef})`,
];
```
## Coverage
Supported families include date/time construction, extraction, workday and network-day calculations, year fractions, week numbers, today/current time, and end-of-month helpers.
@@ -0,0 +1,34 @@
# Engineering Formulas
Engineering formulas cover complex numbers, Bessel functions, bitwise operations, unit conversion, and number-base conversion.
## Formula Pattern
```ts
const formulaBlock = sheet.getRange(outputRange).write({
formulas: formulaMatrix,
});
workbook.recalculate();
const results = formulaBlock.values;
```
## Common Shapes
```ts
const formulas = [
`=COMPLEX(${realRef},${imaginaryRef})`,
`=IMSUM(${complexRangeRef})`,
`=IMPRODUCT(${complexRangeRef})`,
`=IMABS(${complexRef})`,
`=CONVERT(${valueRef},${fromUnitRef},${toUnitRef})`,
`=BIN2DEC(${binaryRef})`,
`=DEC2HEX(${decimalRef})`,
`=BITAND(${valueRef1},${valueRef2})`,
`=BITOR(${valueRef1},${valueRef2})`,
`=BESSELJ(${valueRef},${orderRef})`,
];
```
## Coverage
Supported families include complex arithmetic, bitwise functions, base conversions, Bessel functions, error functions, delta/threshold helpers, and unit conversions.
@@ -0,0 +1,32 @@
# Financial Formulas
Financial formulas cover loans, rates, cash flows, depreciation, securities, treasury bills, and coupon calculations.
## Formula Pattern
```ts
const formulaBlock = sheet.getRange(outputRange).write({
formulas: formulaMatrix,
});
workbook.recalculate();
const results = formulaBlock.values;
```
## Common Shapes
```ts
const formulas = [
`=PMT(${rateRef},${periodsRef},${presentValueRef})`,
`=PV(${rateRef},${periodsRef},${paymentRef})`,
`=FV(${rateRef},${periodsRef},${paymentRef})`,
`=NPV(${rateRef},${cashFlowRangeRef})`,
`=IRR(${cashFlowRangeRef})`,
`=XNPV(${rateRef},${cashFlowRangeRef},${dateRangeRef})`,
`=XIRR(${cashFlowRangeRef},${dateRangeRef})`,
`=RATE(${periodsRef},${paymentRef},${presentValueRef})`,
];
```
## Coverage
Supported families include payment and present/future value, net present value, return rate, depreciation, discount/yield, coupon date math, accrued interest, treasury bills, and compatibility variants.
@@ -0,0 +1,34 @@
# Information Formulas
Information formulas inspect value types, errors, blank cells, sheet indexes, and references.
## Formula Pattern
```ts
const formulaBlock = sheet.getRange(outputRange).write({
formulas: formulaMatrix,
});
workbook.recalculate();
const results = formulaBlock.values;
```
## Common Shapes
```ts
const formulas = [
`=ISBLANK(${valueRef})`,
`=ISNUMBER(${valueRef})`,
`=ISTEXT(${valueRef})`,
`=ISLOGICAL(${valueRef})`,
`=ISERROR(${valueRef})`,
`=ISNA(${valueRef})`,
`=TYPE(${valueRef})`,
`=ERROR.TYPE(${valueRef})`,
`=SHEET(${referenceRef})`,
`=SHEETS(${referenceRef})`,
];
```
## Coverage
Supported families include type predicates, error predicates, blank checks, number/text/logical checks, N conversion, sheet lookup, and error type lookup.
@@ -0,0 +1,39 @@
# Logical Formulas
Logical formulas branch, combine conditions, and handle error values. Follow the main skill’s formula policy and the [XLSX compatibility guidance](../API_QUICK_START.md#known-formulaexport-limitations-not-exhaustive).
## Formula Pattern
```ts
const formulaBlock = sheet.getRange(outputRange).write({
formulas: formulaMatrix,
});
workbook.recalculate();
const results = formulaBlock.values;
```
## Boolean And Branching Shapes
```ts
const formulas = [
`=TRUE()`,
`=FALSE()`,
`=NA()`,
`=AND(${conditionRef1},${conditionRef2})`,
`=OR(${conditionRef1},${conditionRef2})`,
`=NOT(${conditionRef})`,
`=XOR(${conditionRef1},${conditionRef2})`,
`=IF(${conditionRef},${trueValueRef},${falseValueRef})`,
`=_xlfn.IFS(${conditionRef1},${valueRef1},${conditionRef2},${valueRef2})`,
`=SWITCH(${valueRef},${caseRef1},${resultRef1},${defaultRef})`,
];
```
## Error Handling Shapes
```ts
const formulas = [
`=IFERROR(${valueRef},${replacementRef})`,
`=IFNA(${valueRef},${replacementRef})`,
];
```
@@ -0,0 +1,24 @@
# Lookup And Reference Formulas
Lookup and reference formulas locate values and return addresses or dimensions. Follow the main skill’s scalar-formula policy and the [XLSX compatibility guidance](../API_QUICK_START.md#known-formulaexport-limitations-not-exhaustive).
## Formula Pattern
```ts
const formulaBlock = sheet.getRange(outputRange).write({
formulas: formulaMatrix,
});
workbook.recalculate();
const results = formulaBlock.values;
```
## Common Shapes
```ts
const formulas = [
`=_xlfn.XLOOKUP(${lookupRef},${lookupRangeRef},${returnRangeRef})`,
`=VLOOKUP(${lookupRef},${tableRangeRef},${columnIndexRef},${exactRef})`,
`=INDEX(${rangeRef},${rowIndexRef},${columnIndexRef})`,
`=MATCH(${lookupRef},${lookupRangeRef},${matchModeRef})`,
];
```
@@ -0,0 +1,33 @@
# Math And Trig Formulas
Math and trigonometry formulas cover arithmetic, rounding, aggregation, matrix math, random values, base conversion, and trig functions.
## Formula Pattern
```ts
const formulaBlock = sheet.getRange(outputRange).write({
formulas: formulaMatrix,
});
workbook.recalculate();
const results = formulaBlock.values;
```
## Common Shapes
```ts
const formulas = [
`=SUM(${rangeRef})`,
`=PRODUCT(${rangeRef})`,
`=ROUND(${valueRef},${digits})`,
`=POWER(${valueRef},${power})`,
`=MOD(${valueRef},${divisor})`,
`=SIN(${angleRef})`,
`=COS(${angleRef})`,
`=TAN(${angleRef})`,
`=MMULT(${matrixARef},${matrixBRef})`,
];
```
## Coverage
Supported families include aggregate math, rounding, logarithms, powers, matrix functions, random generators, trig, hyperbolic trig, Roman/base conversion, subtotaling, and compatibility variants.
@@ -0,0 +1,32 @@
# Statistical Formulas
Statistical formulas summarize, rank, distribute, correlate, and forecast values.
## Formula Pattern
```ts
const formulaBlock = sheet.getRange(outputRange).write({
formulas: formulaMatrix,
});
workbook.recalculate();
const results = formulaBlock.values;
```
## Common Shapes
```ts
const formulas = [
`=AVERAGE(${rangeRef})`,
`=MEDIAN(${rangeRef})`,
`=STDEV.S(${rangeRef})`,
`=VAR.P(${rangeRef})`,
`=QUARTILE(${rangeRef},${quartileIndex})`,
`=CORREL(${xRangeRef},${yRangeRef})`,
`=FORECAST.LINEAR(${xRef},${knownYRangeRef},${knownXRangeRef})`,
`=FORECAST.ETS(${targetDateRef},${valuesRangeRef},${timelineRangeRef})`,
];
```
## Coverage
Supported families include averages, counts, rank and percentile functions, variance and standard deviation, distributions, regression, covariance/correlation, forecasting, and compatibility names.
@@ -0,0 +1,33 @@
# Text Formulas
Text formulas transform, search, split, join, format, and extract strings.
## Formula Pattern
```ts
const formulaBlock = sheet.getRange(outputRange).write({
formulas: formulaMatrix,
});
workbook.recalculate();
const results = formulaBlock.values;
```
## Common Shapes
```ts
const formulas = [
`=TEXT(${valueRef},${formatRef})`,
`=CONCAT(${rangeRef})`,
`=_xlfn.TEXTJOIN(${delimiterRef},${ignoreEmptyRef},${rangeRef})`,
`=LEFT(${textRef},${countRef})`,
`=RIGHT(${textRef},${countRef})`,
`=MID(${textRef},${startRef},${countRef})`,
`=FIND(${needleRef},${textRef})`,
`=SEARCH(${needleRef},${textRef})`,
`=SUBSTITUTE(${textRef},${oldTextRef},${newTextRef})`,
];
```
## Coverage
Supported families include length, casing, replacement, extraction, joining, splitting, number-to-text formatting, Unicode helpers, and regex helpers.
@@ -0,0 +1,62 @@
# Comments
Workbook comments use people, threads, replies, reactions, and thread state.
## Current Author
```ts
workbook.comments.setSelf({
displayName,
initials,
email,
});
```
## Person Inline Type
```ts
type PersonConfig = {
id?: string;
displayName: string;
initials?: string;
email?: string;
avatarUrl?: string;
};
```
## Cell And Range Threads
```ts
const cellThread = workbook.comments.addThread(
{ cell: sheet.getRange(cellAddress) },
bodyText,
);
const rangeThread = workbook.comments.addThread(
{ range: sheet.getRange(rangeAddress) },
bodyText,
);
```
## Thread Inline Types
```ts
type WorkbookCommentTarget =
| { cell: Range }
| { range: Range };
type ThreadAddOptions = {
author?: Person | PersonConfig | { id: string };
createdAt?: string;
position?: { x: number; y: number; unit?: "px" | "emu" };
};
```
## Replies And State
```ts
const reply = cellThread.addReply(replyText);
reply.toggleReaction(reactionText);
cellThread.resolve();
cellThread.reopen();
```
@@ -0,0 +1,81 @@
# Conditional Formatting
Use `range.conditionalFormats` to add formatting rules to ranges.
## Rule Pattern
```ts
range.conditionalFormats.add(ruleType, {
operator,
formula,
format,
});
```
Choose `ruleType`, `operator`, color, and style strings from the inline types below.
## Rule Inline Types
```ts
type ConditionalFormatRuleType =
| "cellIs" | "CellValue" | "Custom" | "expression"
| "colorScale" | "dataBar" | "iconSet"
| "containsText" | "notContainsText" | "beginsWith" | "endsWith"
| "containsBlanks" | "notContainsBlanks" | "containsErrors" | "notContainsErrors"
| "duplicateValues" | "uniqueValues" | "timePeriod" | "top10" | "aboveAverage";
type CellIsOperator =
| "greaterThan"
| "greaterThanOrEqual"
| "lessThan"
| "lessThanOrEqual"
| "equal"
| "notEqual"
| "between"
| "notBetween";
type ConditionalFormatConfig =
| { operator: CellIsOperator; formula: string | number | Array<string | number>; format?: DifferentialFormatConfig }
| { formula: string | number; format?: DifferentialFormatConfig }
| { colors?: ColorConfig[]; thresholds?: CfvoInput[] }
| { color?: ColorConfig; thresholds?: CfvoInput[]; gradient?: boolean }
| { iconSet: string; showValue?: boolean; reverse?: boolean; thresholds?: CfvoInput[] }
| { text: string; format?: DifferentialFormatConfig }
| { timePeriod: "yesterday" | "today" | "tomorrow" | "last7Days" | "lastWeek" | "thisWeek" | "nextWeek" | "lastMonth" | "thisMonth" | "nextMonth"; format?: DifferentialFormatConfig }
| { rank?: number; percent?: boolean; bottom?: boolean; format?: DifferentialFormatConfig }
| { aboveAverage?: boolean; equalAverage?: boolean; stdDev?: number; format?: DifferentialFormatConfig };
type DifferentialFormatConfig = {
fill?: FillConfig;
font?: { bold?: boolean; italic?: boolean; color?: ColorConfig };
border?: RangeBordersConfig;
numberFormat?: string;
};
type CfvoInput =
| "min"
| "max"
| number
| `${number}%`
| { type: "min" | "max" | "num" | "percent" | "percentile"; value?: string | number };
```
## Custom Rule
```ts
range.conditionalFormats.addCustom(expression, {
fill,
font,
border,
});
```
## Rule Families
Supported rule families include cell value, custom expression, text, blank/error, duplicate/unique, time period, top/bottom, above/below average, color scale, data bar, and icon set.
## Clear Rules
```ts
range.conditionalFormats.deleteAll();
```
@@ -0,0 +1,31 @@
## Data tables (`worksheet.dataTables`)
Use data tables to project a formula across a row/column grid.
### Two-variable data table
```ts
const sheet = workbook.worksheets.add("TwoVariable");
sheet.getRange("B3").values = [[0.095]]; // rate
sheet.getRange("B4").values = [[360]]; // periods
sheet.getRange("B5").values = [[80000]]; // principal
sheet.getRange("C2").formulas = [[`=PMT(B3/12,B4,-B5)`]];
sheet.getRange("C3:C5").values = [[0.09], [0.0925], [0.095]];
sheet.getRange("D2:E2").values = [[180, 360]];
sheet.dataTables.add("D3:E5", {
rowInput: "B4",
columnInput: "B3",
});
workbook.recalculate();
```
### Single-variable (row input only)
```ts
sheet.dataTables.add("D3:E3", { rowInput: "B4" });
workbook.recalculate();
```
@@ -0,0 +1,73 @@
# Data Validations
Use range-level or worksheet-level data validation config.
## Range Assignment
```ts
range.dataValidation = validationConfig;
```
## Rule Config
```ts
range.dataValidation.rule = {
type,
formula1,
formula2,
values,
operator,
};
range.dataValidation.prompt = promptConfig;
range.dataValidation.errorAlert = errorAlertConfig;
range.dataValidation.ignoreBlanks = ignoreBlanks;
range.dataValidation.inCellDropDown = inCellDropDown;
```
## Validation Inline Types
```ts
type DataValidationRule = {
type: "none" | "whole" | "decimal" | "list" | "date" | "time" | "textLength" | "custom";
operator?:
| "between"
| "notBetween"
| "equal"
| "notEqual"
| "lessThan"
| "lessThanOrEqual"
| "greaterThan"
| "greaterThanOrEqual";
formula1?: string | number;
formula2?: string | number;
values?: string[];
};
type ValidationConfig = {
rule?: DataValidationRule | null;
prompt?: { title?: string; message?: string; show?: boolean } | null;
errorAlert?: {
title?: string;
message?: string;
style?: "stop" | "warning" | "information";
show?: boolean;
} | null;
ignoreBlanks?: boolean;
inCellDropDown?: boolean;
};
```
## Collection Add
```ts
sheet.dataValidations.add({
range,
rule,
prompt,
errorAlert,
ignoreBlanks,
inCellDropDown,
});
```
Validation type, operator, and error style values are the strings listed above.
@@ -0,0 +1,43 @@
## Defined names (`workbook.names`, `worksheet.names`)
Use defined names for reusable ranges and workbook functions.
### Named ranges
Workbook-scoped named range:
```ts
const data = workbook.worksheets.add("Data");
data.getRange("A1:A3").values = [[1], [2], [3]];
workbook.names.addRange("SalesRange", "Data!$A$1:$A$3", {
description: "Input sales data",
});
data.getRange("B1").formulas = [["=SUM(SalesRange)"]];
workbook.recalculate();
```
Sheet-scoped named range:
```ts
const sheet1 = workbook.worksheets.add("Sheet1");
sheet1.names.addRange("LocalRange", "Sheet1!$A$1:$A$10");
sheet1.getRange("B1").formulas = [["=SUM(LocalRange)"]];
workbook.recalculate();
```
### Named functions (LAMBDA)
```ts
workbook.names.addFunction("AddTax", {
lambda: "LAMBDA(price, tax, price*(1+tax))", // export may auto-prefix "="
description: "Adds tax to a price",
parameters: [
{ name: "price", description: "Base price" },
{ name: "tax", description: "Tax rate (e.g. 0.1)" },
],
returns: "Taxed price",
});
```
@@ -0,0 +1,151 @@
# Worksheet Drawings
Worksheets support charts and shapes anchored to the cell grid.
## Units
- Anchor row and column indexes are zero-based.
- Offsets and extents use pixels.
- Use `rowOffsetPx`, `colOffsetPx`, `widthPx`, and `heightPx`.
## Chart From Source Cells
Bind charts to source ranges so edits update their data. Define shared axis
configs at the top level of the persistent JavaScript REPL:
```js
var chartStyle = {
axisText: { typeface: "Arial", fontSize: 13, fill: "dk2" },
};
```
Inside a session callback:
```js
const chart = sheet.charts.add("bar", sourceRange);
chart.setPosition(startCell, endCell);
chart.xAxis = { textStyle: chartStyle.axisText };
chart.yAxis = { textStyle: chartStyle.axisText, numberFormatCode: "#,##0", numberFormatSourceLinked: false };
```
Apply the workbook's font, palette, units, and [chart guidance](../API_QUICK_START.md#charts).
For line charts, set the series line stroke explicitly. Use config-object chart
creation for custom series; range-backed charts are the default when cells hold
the source data. The common [spreadsheet quick start](../API_QUICK_START.md#charts) lists range binding
and XLSX chart-type limitations.
## Chart Inline Types
```ts
type WorksheetChartType =
| "bar" | "line" | "area" | "pie" | "doughnut" | "scatter"
| "bubble" | "radar" | "stock";
type WorksheetChartConfig = {
from?: { row: number; col: number; rowOffsetPx?: number; colOffsetPx?: number };
to?: { row: number; col: number; rowOffsetPx?: number; colOffsetPx?: number };
extent?: { widthPx?: number; heightPx?: number };
title?: string;
titleTextStyle?: TextStyleConfig;
categories?: string[];
series?: Array<{ name: string; values?: number[]; categories?: string[]; fill?: FillConfig; line?: LineConfig }>;
hasLegend?: boolean;
legend?: { position?: "left" | "top" | "topRight" | "right" | "bottom"; overlay?: boolean; textStyle?: TextStyleConfig };
xAxis?: ChartAxisConfig;
yAxis?: ChartAxisConfig;
dataLabels?: { showValue?: boolean; position?: "center" | "inEnd" | "outEnd"; textStyle?: TextStyleConfig };
dataTable?: { visible?: boolean; showLegendKey?: boolean; textStyle?: TextStyleConfig };
};
type TextStyleConfig = {
typeface?: string;
bold?: boolean;
italic?: boolean;
fontSize?: number;
color?: ColorConfig;
fill?: FillConfig;
alignment?: "left" | "center" | "right" | "justify";
};
type ChartAxisConfig = {
title?: string | { text?: string; textStyle?: TextStyleConfig };
min?: number;
max?: number;
numberFormatCode?: string;
numberFormatSourceLinked?: boolean;
position?: "left" | "right" | "top" | "bottom";
tickLabelPosition?: "high" | "low" | "nextTo" | string;
textStyle?: TextStyleConfig;
line?: LineConfig;
majorGridlines?: LineConfig | null;
minorGridlines?: LineConfig | null;
};
```
## Chart From Range
```ts
const chart = sheet.charts.add(chartType, sourceRange, seriesBy);
chart.setPosition(startRange, endRange);
chart.width = widthPx;
chart.height = heightPx;
```
## Shape Config
```ts
const shape = sheet.shapes.add({
geometry,
anchor,
fill,
line,
name,
});
```
## Shape Inline Type
```ts
type WorksheetShapeConfig = {
geometry: string; // common: "rect", "roundRect", "ellipse", "textbox"; full list is the slide shape preset list
anchor?: DrawingAnchorConfig;
fill?: FillConfig;
line?: LineConfig;
name?: string;
};
type DrawingAnchorConfig = {
from: { row: number; col: number; rowOffsetPx?: number; colOffsetPx?: number };
to?: { row: number; col: number; rowOffsetPx?: number; colOffsetPx?: number };
extent?: { widthPx?: number; heightPx?: number };
};
```
## Rebuild And Layout
For an authorized rebuild, delete only the drawings being replaced.
```ts
const drawings = [...sheet.charts.items, ...sheet.shapes.items];
sheet.autoLayoutDrawings(drawings, {
direction,
frame,
gap,
padding,
});
```
## Auto Layout Inline Type
```ts
type WorksheetDrawingAutoLayoutOptions = {
direction?: "vertical" | "horizontal" | "grid";
align?: "start" | "center" | "end";
columns?: number; // used for grid
gap?: number;
padding?: number;
frame?:
| { left: number; top: number; width: number; height: number }
| { startCell: string; width: number; height: number };
};
```
@@ -0,0 +1,647 @@
# Workbook.apply enums (v0)
Shared enum value lists referenced by `Workbook.apply` ops.
## `props.axis.maxMode`
- `custom`
- `group`
- `individual`
- `unspecified`
## `props.axis.minMode`
- `custom`
- `group`
- `individual`
- `unspecified`
## `props.borders.preset`
- `all`
- `doubleBottom`
- `inside`
- `none`
- `outside`
## `props.chartType`
- `area`
- `area3D`
- `bar`
- `bar3D`
- `boxWhisker`
- `bubble`
- `combo`
- `doughnut`
- `funnel`
- `histogram`
- `line`
- `line3D`
- `map`
- `ofPie`
- `pareto`
- `pie`
- `pie3D`
- `radar`
- `scatter`
- `stock`
- `sunburst`
- `surface`
- `surface3D`
- `treemap`
- `waterfall`
## `props.displayBlanksAs`
- `gap`
- `span`
- `zero`
## `props.displayEmptyCellsAs`
- `gap`
- `span`
- `unspecified`
- `zero`
## `props.errorAlert.style`
- `information`
- `stop`
- `warning`
## `props.fill.color.value`
- `accent1`
- `accent2`
- `accent3`
- `accent4`
- `accent5`
- `accent6`
- `bg1`
- `bg2`
- `dk1`
- `dk2`
- `folHlink`
- `hlink`
- `lt1`
- `lt2`
- `tx1`
- `tx2`
## `props.fill.gradientKind`
- `linear`
- `path`
## `props.fill.pattern.type`
- `cross`
- `darkDown`
- `darkGray`
- `darkGrid`
- `darkHorizontal`
- `darkTrellis`
- `darkUp`
- `darkVertical`
- `dashedDownwardDiagonal`
- `dashedHorizontal`
- `dashedUpwardDiagonal`
- `dashedVertical`
- `diagonalBrick`
- `diagonalCross`
- `divot`
- `dotGrid`
- `dottedDiamond`
- `downwardDiagonal`
- `gray0625`
- `gray125`
- `horizontal`
- `horizontalBrick`
- `largeCheck`
- `largeConfetti`
- `largeGrid`
- `lightDown`
- `lightGray`
- `lightGrid`
- `lightHorizontal`
- `lightTrellis`
- `lightUp`
- `lightVertical`
- `mediumGray`
- `narrowHorizontal`
- `narrowVertical`
- `none`
- `openDiamond`
- `percent10`
- `percent20`
- `percent25`
- `percent30`
- `percent40`
- `percent5`
- `percent50`
- `percent60`
- `percent70`
- `percent75`
- `percent80`
- `percent90`
- `plaid`
- `shingle`
- `smallCheck`
- `smallConfetti`
- `smallGrid`
- `solid`
- `solidDiamond`
- `sphere`
- `trellis`
- `upwardDiagonal`
- `vertical`
- `wave`
- `weave`
- `wideDownwardDiagonal`
- `wideUpwardDiagonal`
- `zigZag`
## `props.geometry`
- `accentBorderCallout1`
- `accentBorderCallout2`
- `accentBorderCallout3`
- `accentCallout1`
- `accentCallout2`
- `accentCallout3`
- `actionButtonBackPrevious`
- `actionButtonBeginning`
- `actionButtonBlank`
- `actionButtonDocument`
- `actionButtonEnd`
- `actionButtonForwardNext`
- `actionButtonHelp`
- `actionButtonHome`
- `actionButtonInformation`
- `actionButtonMovie`
- `actionButtonReturn`
- `actionButtonSound`
- `arc`
- `bentArrow`
- `bentConnector2`
- `bentConnector3`
- `bentConnector4`
- `bentConnector5`
- `bentUpArrow`
- `bevel`
- `blockArc`
- `borderCallout1`
- `borderCallout2`
- `borderCallout3`
- `bracePair`
- `bracketPair`
- `callout1`
- `callout2`
- `callout3`
- `can`
- `chartPlus`
- `chartStar`
- `chartX`
- `chevron`
- `chord`
- `circularArrow`
- `cloud`
- `cloudCallout`
- `corner`
- `cornerTabs`
- `cube`
- `curvedConnector2`
- `curvedConnector3`
- `curvedConnector4`
- `curvedConnector5`
- `curvedDownArrow`
- `curvedLeftArrow`
- `curvedRightArrow`
- `curvedUpArrow`
- `decagon`
- `diagStripe`
- `diamond`
- `dodecagon`
- `donut`
- `doubleWave`
- `downArrow`
- `downArrowCallout`
- `ellipse`
- `ellipseRibbon`
- `ellipseRibbon2`
- `flowChartAlternateProcess`
- `flowChartCollate`
- `flowChartConnector`
- `flowChartDecision`
- `flowChartDelay`
- `flowChartDisplay`
- `flowChartDocument`
- `flowChartExtract`
- `flowChartInputOutput`
- `flowChartInternalStorage`
- `flowChartMagneticDisk`
- `flowChartMagneticDrum`
- `flowChartMagneticTape`
- `flowChartManualInput`
- `flowChartManualOperation`
- `flowChartMerge`
- `flowChartMultidocument`
- `flowChartOfflineStorage`
- `flowChartOffpageConnector`
- `flowChartOnlineStorage`
- `flowChartOr`
- `flowChartPredefinedProcess`
- `flowChartPreparation`
- `flowChartProcess`
- `flowChartPunchedCard`
- `flowChartPunchedTape`
- `flowChartSort`
- `flowChartSummingJunction`
- `flowChartTerminator`
- `foldedCorner`
- `frame`
- `funnel`
- `gear6`
- `gear9`
- `halfFrame`
- `heart`
- `heptagon`
- `hexagon`
- `homePlate`
- `horizontalScroll`
- `irregularSeal1`
- `irregularSeal2`
- `leftArrow`
- `leftArrowCallout`
- `leftBrace`
- `leftBracket`
- `leftCircularArrow`
- `leftRightArrow`
- `leftRightArrowCallout`
- `leftRightCircularArrow`
- `leftRightRibbon`
- `leftRightUpArrow`
- `leftUpArrow`
- `lightningBolt`
- `line`
- `lineInv`
- `mathDivide`
- `mathEqual`
- `mathMinus`
- `mathMultiply`
- `mathNotEqual`
- `mathPlus`
- `moon`
- `noSmoking`
- `nonIsoscelesTrapezoid`
- `notchedRightArrow`
- `octagon`
- `parallelogram`
- `pentagon`
- `pie`
- `pieWedge`
- `plaque`
- `plaqueTabs`
- `plus`
- `quadArrow`
- `quadArrowCallout`
- `rect`
- `ribbon`
- `ribbon2`
- `rightArrow`
- `rightArrowCallout`
- `rightBrace`
- `rightBracket`
- `round1Rect`
- `round2DiagRect`
- `round2SameRect`
- `roundRect`
- `rtTriangle`
- `smileyFace`
- `snip1Rect`
- `snip2DiagRect`
- `snip2SameRect`
- `snipRoundRect`
- `squareTabs`
- `star10`
- `star12`
- `star16`
- `star24`
- `star32`
- `star4`
- `star5`
- `star6`
- `star7`
- `star8`
- `straightConnector1`
- `stripedRightArrow`
- `sun`
- `swooshArrow`
- `teardrop`
- `textbox`
- `trapezoid`
- `triangle`
- `upArrow`
- `upArrowCallout`
- `upDownArrow`
- `upDownArrowCallout`
- `uturnArrow`
- `verticalScroll`
- `wave`
- `wedgeEllipseCallout`
- `wedgeRectCallout`
- `wedgeRoundRectCallout`
## `props.horizontalAlignment`
- `Center`
- `CenterAcrossSelection`
- `Distributed`
- `Fill`
- `General`
- `Justify`
- `Left`
- `Right`
## `props.legend.position`
- `bottom`
- `left`
- `right`
- `top`
- `topRight`
## `props.line.style`
- `dash-dot`
- `dash-dot-dot`
- `dashed`
- `dotted`
- `solid`
## `props.rule.format.fill.color.value`
- `accent1`
- `accent2`
- `accent3`
- `accent4`
- `accent5`
- `accent6`
- `bg1`
- `bg2`
- `dk1`
- `dk2`
- `folHlink`
- `hlink`
- `lt1`
- `lt2`
- `tx1`
- `tx2`
## `props.rule.format.fill.gradientKind`
- `linear`
- `path`
## `props.rule.format.fill.pattern.type`
- `cross`
- `darkDown`
- `darkGray`
- `darkGrid`
- `darkHorizontal`
- `darkTrellis`
- `darkUp`
- `darkVertical`
- `dashedDownwardDiagonal`
- `dashedHorizontal`
- `dashedUpwardDiagonal`
- `dashedVertical`
- `diagonalBrick`
- `diagonalCross`
- `divot`
- `dotGrid`
- `dottedDiamond`
- `downwardDiagonal`
- `gray0625`
- `gray125`
- `horizontal`
- `horizontalBrick`
- `largeCheck`
- `largeConfetti`
- `largeGrid`
- `lightDown`
- `lightGray`
- `lightGrid`
- `lightHorizontal`
- `lightTrellis`
- `lightUp`
- `lightVertical`
- `mediumGray`
- `narrowHorizontal`
- `narrowVertical`
- `none`
- `openDiamond`
- `percent10`
- `percent20`
- `percent25`
- `percent30`
- `percent40`
- `percent5`
- `percent50`
- `percent60`
- `percent70`
- `percent75`
- `percent80`
- `percent90`
- `plaid`
- `shingle`
- `smallCheck`
- `smallConfetti`
- `smallGrid`
- `solid`
- `solidDiamond`
- `sphere`
- `trellis`
- `upwardDiagonal`
- `vertical`
- `wave`
- `weave`
- `wideDownwardDiagonal`
- `wideUpwardDiagonal`
- `zigZag`
## `props.rule.operator`
- `between`
- `equal`
- `greaterThan`
- `greaterThanOrEqual`
- `lessThan`
- `lessThanOrEqual`
- `notBetween`
- `notEqual`
## `props.rule.thresholds[].type`
- `max`
- `min`
- `num`
- `percent`
- `percentile`
## `props.rule.type`
- `custom`
- `date`
- `decimal`
- `list`
- `none`
- `textLength`
- `time`
- `whole`
## `props.series[].marker.symbol`
- `circle`
- `diamond`
- `dot`
- `none`
- `plus`
- `square`
- `star`
- `triangle`
- `x`
## `props.series[].stroke.fill.color.value`
- `accent1`
- `accent2`
- `accent3`
- `accent4`
- `accent5`
- `accent6`
- `bg1`
- `bg2`
- `dk1`
- `dk2`
- `folHlink`
- `hlink`
- `lt1`
- `lt2`
- `tx1`
- `tx2`
## `props.series[].stroke.fill.gradientKind`
- `linear`
- `path`
## `props.series[].stroke.fill.pattern.type`
- `cross`
- `darkDown`
- `darkGray`
- `darkGrid`
- `darkHorizontal`
- `darkTrellis`
- `darkUp`
- `darkVertical`
- `dashedDownwardDiagonal`
- `dashedHorizontal`
- `dashedUpwardDiagonal`
- `dashedVertical`
- `diagonalBrick`
- `diagonalCross`
- `divot`
- `dotGrid`
- `dottedDiamond`
- `downwardDiagonal`
- `gray0625`
- `gray125`
- `horizontal`
- `horizontalBrick`
- `largeCheck`
- `largeConfetti`
- `largeGrid`
- `lightDown`
- `lightGray`
- `lightGrid`
- `lightHorizontal`
- `lightTrellis`
- `lightUp`
- `lightVertical`
- `mediumGray`
- `narrowHorizontal`
- `narrowVertical`
- `none`
- `openDiamond`
- `percent10`
- `percent20`
- `percent25`
- `percent30`
- `percent40`
- `percent5`
- `percent50`
- `percent60`
- `percent70`
- `percent75`
- `percent80`
- `percent90`
- `plaid`
- `shingle`
- `smallCheck`
- `smallConfetti`
- `smallGrid`
- `solid`
- `solidDiamond`
- `sphere`
- `trellis`
- `upwardDiagonal`
- `vertical`
- `wave`
- `weave`
- `wideDownwardDiagonal`
- `wideUpwardDiagonal`
- `zigZag`
## `props.series[].stroke.style`
- `dash-dot`
- `dash-dot-dot`
- `dashed`
- `dotted`
- `solid`
## `props.seriesColor.value`
- `accent1`
- `accent2`
- `accent3`
- `accent4`
- `accent5`
- `accent6`
- `bg1`
- `bg2`
- `dk1`
- `dk2`
- `folHlink`
- `hlink`
- `lt1`
- `lt2`
- `tx1`
- `tx2`
## `props.type`
- `column`
- `line`
- `stacked`
## `props.verticalAlignment`
- `bottom`
- `middle`
- `top`
@@ -0,0 +1,84 @@
# Worksheet Images
Use `sheet.images.add(...)` to attach images to cell-grid anchors.
Download remote images first, then pass the local `path` or embedded `blob` bytes.
## Add Image
```ts
const image = sheet.images.add({
path,
blob,
dataUrl,
prompt,
alt,
anchor,
});
const icon = sheet.images.add({
svg: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10" fill="#2563eb"/></svg>',
anchor: { from: { row: 1, col: 5 }, extent: { widthPx: 48, heightPx: 48 } },
});
```
## Image Inline Types
```ts
type WorksheetImageConfig = ImageSource & {
alt?: string;
contentType?: string;
anchor?: DrawingAnchorConfig;
};
type ImageSource =
| { path: string }
| { svg: string }
| { blob: ArrayBuffer }
| { dataUrl: string }
| { prompt: string };
```
## Anchor
```ts
const anchor = {
from,
to,
extent,
};
```
`from`, `to`, and `extent` use the same zero-based anchor and pixel extent shapes as worksheet charts and shapes.
## Anchor Inline Type
```ts
type DrawingAnchorConfig = {
from: AnchorInput;
to?: AnchorInput;
extent?: {
widthPx?: number;
heightPx?: number;
widthEmu?: number;
heightEmu?: number;
};
};
type AnchorInput = {
row: number;
col: number;
rowOffsetPx?: number;
colOffsetPx?: number;
rowOffsetEmu?: number;
colOffsetEmu?: number;
};
```
## Edit
```ts
image.anchor = anchor;
image.alt = altText;
image.replace(sourceConfig);
image.delete();
```
@@ -0,0 +1,86 @@
# chart ops
Ops in the `chart.*` namespace for `Workbook.apply`.
## Ops index
- `chart.add`: Add a chart anchored to worksheet cells.
## `chart.add`
Add a chart anchored to worksheet cells.
**Required fields**
- `op`
- `props`
- `sheet`
- `props.anchor`
- `props.chartType`
**Optional fields**
- `as`
- `props.categories`
- `props.dataLabels`
- `props.displayBlanksAs`
- `props.hasLegend`
- `props.legend`
- `props.series`
- `props.title`
**Enums**
- `props.chartType`: See [enums](../enums.md).
- `props.displayBlanksAs`: See [enums](../enums.md).
- `props.legend.position`: See [enums](../enums.md).
- `props.series[].marker.symbol`: See [enums](../enums.md).
- `props.series[].stroke.fill.color.value`: See [enums](../enums.md).
- `props.series[].stroke.fill.gradientKind`: See [enums](../enums.md).
- `props.series[].stroke.fill.pattern.type`: See [enums](../enums.md).
- `props.series[].stroke.style`: See [enums](../enums.md).
**Examples**
```json
{
"op": "chart.add",
"sheet": "Charts",
"props": {
"chartType": "line",
"anchor": {
"from": {
"row": 1,
"col": 1,
"rowOffsetPx": 4,
"colOffsetPx": 8
},
"extent": {
"widthPx": 520,
"heightPx": 280
}
},
"title": "Milky Way Star Birth Rate",
"categories": [
"2020",
"2021",
"2022",
"2023"
],
"series": [
{
"name": "Milky Way",
"values": [
1.8,
1.9,
2,
2.2
]
}
],
"hasLegend": true,
"legend": {
"position": "bottom"
},
"dataLabels": {
"showValue": true
}
}
}
```
@@ -0,0 +1,29 @@
# comments ops
Ops in the `comments.*` namespace for `Workbook.apply`.
## Ops index
- `comments.self.set`: Set the current comment author identity.
## `comments.self.set`
Set the current comment author identity.
**Required fields**
- `op`
- `person`
**Optional fields**
- (none)
**Examples**
```json
{
"op": "comments.self.set",
"person": {
"displayName": "Artifact Bot",
"initials": "AB"
}
}
```
@@ -0,0 +1,52 @@
# conditionalformat ops
Ops in the `conditionalformat.*` namespace for `Workbook.apply`.
## Ops index
- `conditionalformat.add`: Add a conditional formatting rule to a range.
## `conditionalformat.add`
Add a conditional formatting rule to a range.
**Required fields**
- `op`
- `props`
- `target`
- `props.rule`
**Optional fields**
- (none)
**Enums**
- `props.rule.format.fill.color.value`: See [enums](../enums.md).
- `props.rule.format.fill.gradientKind`: See [enums](../enums.md).
- `props.rule.format.fill.pattern.type`: See [enums](../enums.md).
- `props.rule.operator`: See [enums](../enums.md).
- `props.rule.thresholds[].type`: See [enums](../enums.md).
**Examples**
```json
{
"op": "conditionalformat.add",
"target": {
"sheet": "CF",
"range": "A1:A3"
},
"props": {
"rule": {
"type": "cellIs",
"operator": "greaterThan",
"formula": 3,
"format": {
"fill": "accent2",
"font": {
"bold": true,
"color": "accent3"
}
}
}
}
}
```
@@ -0,0 +1,59 @@
# datavalidation ops
Ops in the `datavalidation.*` namespace for `Workbook.apply`.
## Ops index
- `datavalidation.set`: Set data validation rules for a range.
## `datavalidation.set`
Set data validation rules for a range.
**Required fields**
- `op`
- `props`
- `target`
- `props.rule`
**Optional fields**
- `props.errorAlert`
- `props.ignoreBlanks`
- `props.inCellDropDown`
- `props.prompt`
**Enums**
- `props.errorAlert.style`: See [enums](../enums.md).
- `props.rule.operator`: See [enums](../enums.md).
- `props.rule.type`: See [enums](../enums.md).
**Examples**
```json
{
"op": "datavalidation.set",
"target": {
"sheet": "Validation",
"range": "B2:B10"
},
"props": {
"rule": {
"type": "list",
"values": [
"Dog",
"Cat",
"Bat"
]
},
"prompt": {
"title": "Pick an animal",
"show": true
},
"errorAlert": {
"title": "Invalid choice",
"show": true
},
"ignoreBlanks": true,
"inCellDropDown": true
}
}
```
@@ -0,0 +1,47 @@
# image ops
Ops in the `image.*` namespace for `Workbook.apply`.
## Ops index
- `image.add`: Add an image anchored to worksheet cells.
## `image.add`
Add an image anchored to worksheet cells.
**Required fields**
- `op`
- `props`
- `sheet`
**Optional fields**
- `as`
- `props.alt`
- `props.anchor`
- `props.contentType`
- `props.dataUrl`
- `props.path`
- `props.prompt`
- `props.uri`
**Examples**
```json
{
"op": "image.add",
"sheet": "Images",
"props": {
"dataUrl": "data:image/png;base64,...",
"anchor": {
"from": {
"row": 1,
"col": 2
},
"extent": {
"widthPx": 160,
"heightPx": 120
}
}
}
}
```
@@ -0,0 +1,67 @@
# names ops
Ops in the `names.*` namespace for `Workbook.apply`.
## Ops index
- `names.function.add`: Define a workbook or worksheet named function (LAMBDA).
- `names.range.add`: Define a workbook or worksheet named range.
## `names.function.add`
Define a workbook or worksheet named function (LAMBDA).
**Required fields**
- `lambda`
- `name`
- `op`
**Optional fields**
- `description`
- `parameters`
- `returns`
- `sheet`
**Examples**
```json
{
"op": "names.function.add",
"name": "AddTax",
"lambda": "LAMBDA(price, tax, price*(1+tax))",
"description": "Adds tax to a price",
"parameters": [
{
"name": "price",
"description": "Base price"
},
{
"name": "tax",
"description": "Tax rate (e.g. 0.1)"
}
],
"returns": "Taxed price"
}
```
## `names.range.add`
Define a workbook or worksheet named range.
**Required fields**
- `formula`
- `name`
- `op`
**Optional fields**
- `description`
- `sheet`
**Examples**
```json
{
"op": "names.range.add",
"name": "SalesRange",
"formula": "Data!$A$1:$A$3",
"description": "Input sales data"
}
```
@@ -0,0 +1,165 @@
# range ops
Ops in the `range.*` namespace for `Workbook.apply`.
## Ops index
- `range.format.set`: Apply formatting to a range.
- `range.formulas.set`: Set formulas for a range.
- `range.merge`: Merge cells in a range.
- `range.unmerge`: Unmerge any merged blocks intersecting the range.
- `range.values.set`: Set cell values for a range.
## `range.format.set`
Apply formatting to a range.
**Required fields**
- `op`
- `props`
- `target`
**Optional fields**
- `props.borders`
- `props.columnWidth`
- `props.fill`
- `props.font`
- `props.horizontalAlignment`
- `props.numberFormat`
- `props.rowHeight`
- `props.verticalAlignment`
- `props.wrapText`
**Enums**
- `props.borders.preset`: See [enums](../enums.md).
- `props.fill.color.value`: See [enums](../enums.md).
- `props.fill.gradientKind`: See [enums](../enums.md).
- `props.fill.pattern.type`: See [enums](../enums.md).
- `props.horizontalAlignment`: See [enums](../enums.md).
- `props.verticalAlignment`: See [enums](../enums.md).
**Examples**
```json
{
"op": "range.format.set",
"target": {
"sheet": "Scorecard",
"range": "A1:C1"
},
"props": {
"fill": "accent1",
"font": {
"bold": true,
"size": 14
},
"horizontalAlignment": "Center"
}
}
```
## `range.formulas.set`
Set formulas for a range.
**Required fields**
- `formulas`
- `op`
- `target`
**Optional fields**
- (none)
**Examples**
```json
{
"op": "range.formulas.set",
"target": {
"sheet": "Inventory",
"range": "E2"
},
"formulas": [
[
"=AVERAGE(C2:C4)"
]
]
}
```
## `range.merge`
Merge cells in a range.
**Required fields**
- `op`
- `target`
**Optional fields**
- `across`
**Examples**
```json
{
"op": "range.merge",
"target": {
"sheet": "Report",
"range": "A1:D1"
}
}
```
## `range.unmerge`
Unmerge any merged blocks intersecting the range.
**Required fields**
- `op`
- `target`
**Optional fields**
- (none)
**Examples**
```json
{
"op": "range.unmerge",
"target": {
"sheet": "Report",
"range": "A1:D4"
}
}
```
## `range.values.set`
Set cell values for a range.
**Required fields**
- `op`
- `target`
- `values`
**Optional fields**
- (none)
**Examples**
```json
{
"op": "range.values.set",
"target": {
"sheet": "Inventory",
"range": "A1:C2"
},
"values": [
[
"SKU",
"Color",
"Stock"
],
[
"100-001",
"Black",
15
]
]
}
```
@@ -0,0 +1,57 @@
# shape ops
Ops in the `shape.*` namespace for `Workbook.apply`.
## Ops index
- `shape.add`: Add a shape anchored to worksheet cells.
## `shape.add`
Add a shape anchored to worksheet cells.
**Required fields**
- `op`
- `props`
- `sheet`
- `props.geometry`
**Optional fields**
- `as`
- `props.anchor`
- `props.fill`
- `props.line`
**Enums**
- `props.fill.color.value`: See [enums](../enums.md).
- `props.fill.gradientKind`: See [enums](../enums.md).
- `props.fill.pattern.type`: See [enums](../enums.md).
- `props.geometry`: See [enums](../enums.md).
- `props.line.style`: See [enums](../enums.md).
**Examples**
```json
{
"op": "shape.add",
"sheet": "Shapes",
"props": {
"geometry": "rect",
"anchor": {
"from": {
"row": 2,
"col": 3
},
"extent": {
"widthPx": 260,
"heightPx": 140
}
},
"fill": "accent1",
"line": {
"style": "dashed",
"fill": "accent4",
"width": 1
}
}
}
```
@@ -0,0 +1,26 @@
# sheet ops
Ops in the `sheet.*` namespace for `Workbook.apply`.
## Ops index
- `sheet.add`: Add a worksheet to the workbook.
## `sheet.add`
Add a worksheet to the workbook.
**Required fields**
- `op`
**Optional fields**
- `as`
- `name`
**Examples**
```json
{
"op": "sheet.add",
"name": "Inventory"
}
```
@@ -0,0 +1,69 @@
# sparkline ops
Ops in the `sparkline.*` namespace for `Workbook.apply`.
## Ops index
- `sparkline.add`: Create a sparkline group backed by source data.
## `sparkline.add`
Create a sparkline group backed by source data.
**Required fields**
- `op`
- `props`
- `props.sourceData`
- `props.targetRange`
- `props.type`
**Optional fields**
- `props.axis`
- `props.axisColor`
- `props.dateAxisRange`
- `props.displayEmptyCellsAs`
- `props.displayHidden`
- `props.firstMarkerColor`
- `props.highMarkerColor`
- `props.lastMarkerColor`
- `props.lineWeight`
- `props.lowMarkerColor`
- `props.markers`
- `props.markersColor`
- `props.negativeColor`
- `props.seriesColor`
**Enums**
- `props.axis.maxMode`: See [enums](../enums.md).
- `props.axis.minMode`: See [enums](../enums.md).
- `props.displayEmptyCellsAs`: See [enums](../enums.md).
- `props.seriesColor.value`: See [enums](../enums.md).
- `props.type`: See [enums](../enums.md).
**Examples**
```json
{
"op": "sparkline.add",
"props": {
"type": "line",
"targetRange": {
"sheet": "KPIs",
"range": "H2:H3"
},
"sourceData": {
"sheet": "KPIs",
"range": "B2:G3"
},
"dateAxisRange": {
"sheet": "KPIs",
"range": "B1:G1"
},
"seriesColor": "accent1",
"markers": {
"show": true,
"high": true,
"low": true
}
}
}
```
@@ -0,0 +1,71 @@
# table ops
Ops in the `table.*` namespace for `Workbook.apply`.
## Ops index
- `table.add`: Create a table from a range.
- `table.rows.add`: Append or insert rows into a table.
## `table.add`
Create a table from a range.
**Required fields**
- `op`
- `props`
- `props.range`
**Optional fields**
- `as`
- `props.hasHeaders`
- `props.name`
**Examples**
```json
{
"op": "table.add",
"props": {
"range": {
"sheet": "Inventory",
"range": "A1:C3"
},
"hasHeaders": true,
"name": "InventoryTable"
}
}
```
## `table.rows.add`
Append or insert rows into a table.
**Required fields**
- `op`
- `props`
- `target`
- `props.values`
**Optional fields**
- `props.index`
**Examples**
```json
{
"op": "table.rows.add",
"target": {
"name": "InventoryTable",
"sheet": "Inventory"
},
"props": {
"index": null,
"values": [
[
"100-003",
"Denim",
12
]
]
}
}
```
@@ -0,0 +1,97 @@
# thread ops
Ops in the `thread.*` namespace for `Workbook.apply`.
## Ops index
- `thread.add`: Create a threaded comment on a cell or range.
- `thread.reopen`: Reopen a resolved comment thread.
- `thread.reply`: Reply to a comment thread.
- `thread.resolve`: Resolve a comment thread.
## `thread.add`
Create a threaded comment on a cell or range.
**Required fields**
- `body`
- `op`
- `target`
**Optional fields**
- `author`
- `createdAt`
**Examples**
```json
{
"op": "thread.add",
"target": {
"cell": {
"sheet": "Sheet1",
"address": "F5"
}
},
"body": "Cell comment"
}
```
## `thread.reopen`
Reopen a resolved comment thread.
**Required fields**
- `op`
- `target`
**Optional fields**
- (none)
**Examples**
```json
{
"op": "thread.reopen",
"target": "threadId"
}
```
## `thread.reply`
Reply to a comment thread.
**Required fields**
- `body`
- `op`
- `target`
**Optional fields**
- `author`
- `createdAt`
**Examples**
```json
{
"op": "thread.reply",
"target": "threadId",
"body": "Reply on cell"
}
```
## `thread.resolve`
Resolve a comment thread.
**Required fields**
- `op`
- `target`
**Optional fields**
- (none)
**Examples**
```json
{
"op": "thread.resolve",
"target": "threadId"
}
```
@@ -0,0 +1,68 @@
## Ranges API
Use `Worksheet.getRange(address)` to read and write grid data using Excel A1 notation.
### Values
`range.values` is a 2D array of `CellValue`:
- `string | number | boolean | Date | null`
- `null` represents an empty cell
```ts
sheet.getRange("A1:C1").values = [["Date", "Dog", "Resting HR (bpm)"]];
sheet.getRange("A2:C4").values = [
["2025-01-02", "Nova", 58],
["2025-01-03", "Nova", 61],
["2025-01-03", "Comet", 72],
];
```
### Checkboxes
Assign boolean values to create Excel checkbox cells. Use `range.values = null` to clear a range and remove the checkbox control.
```ts
sheet.getRange("A1").values = [[true]];
sheet.getRange("A2").values = [[false]];
sheet.getRange("A1:A2").values = null;
```
### Merged cells
Use `range.merge()` to merge a rectangular range into a single cell region, and `range.unmerge()` to remove merges that intersect the range.
```ts
// Merge a header across columns
sheet.getRange("B1:H1").merge();
// Merge across rows (one merge per row, like Excel “Merge Across”)
sheet.getRange("B2:H4").merge(true);
// Remove merges touching the range
sheet.getRange("B1:H4").unmerge();
```
### Formulas
`range.formulas` is a 2D array of strings. Call `workbook.recalculate()` before reading computed `values`.
```ts
sheet.getRange("E1").values = [["Average HR"]];
sheet.getRange("E2").formulas = [[`=AVERAGE(C2:C4)`]];
workbook.recalculate();
const average = sheet.getRange("E2").values[0]?.[0];
```
### A1 addressing conventions
Supported addressing patterns include:
- `A1` (single cell)
- `A1:C10` (rectangle)
- `A:A` (entire column)
- `2:2` (entire row)
In formulas, quote sheet names that contain spaces/punctuation: `'Cost Summary'!A1`.
@@ -0,0 +1,145 @@
# Range Formatting
Use `range.format` to style cells with fills, fonts, borders, number formats, sizing, and alignment.
## Reusable Formats
Define shared configs at the top level of the persistent JavaScript REPL. Apply
them to ranges inside session callbacks; use object spread for local overrides.
```js
var formats = {
header: { fill: "accent1", font: { bold: true, color: "lt1" } },
amount: { numberFormat: "#,##0.00" },
};
```
```js
sheet.getRange("A1:D1").format = formats.header;
sheet.getRange("B2:D10").format = formats.amount;
sheet.getRange("B11:D11").format = { ...formats.amount, font: { bold: true } };
```
A config is applied at assignment time; changing it later does not restyle
existing ranges. Spread is shallow: merge nested objects explicitly when needed.
Use `workbook.colorScheme = { name, themeColors }` once for new workbooks, with
the XLSX slots below. Reuse those tokens in formats; preserve existing themes
and the task's domain color meanings. `bg*`/`tx*` aliases are not independent
XLSX scheme slots. Font `size` is in points; drawing/chart `fontSize` is in pixels.
## Shared Color And Fill Inline Types
```ts
type ThemeColorName =
| "accent1" | "accent2" | "accent3" | "accent4" | "accent5" | "accent6"
| "dk1" | "lt1" | "dk2" | "lt2"
| "hlink" | "folHlink";
type ColorConfig =
| string
| { type: "rgb"; value: string; transform?: { opacity?: number; lighten?: number; darken?: number } }
| { type: "theme"; value: ThemeColorName; transform?: { opacity?: number; lighten?: number; darken?: number } };
type FillConfig =
| string
| { type: "none" }
| { type: "solid"; color: ColorConfig }
| { type: "gradient"; stops: Array<{ offset: number; color: ColorConfig }>; angleDeg?: number; gradientKind?: "linear" | "path" };
```
## Grouped Format
```ts
range.format = {
fill,
font,
horizontalAlignment,
verticalAlignment,
wrapText,
borders,
numberFormat,
};
```
## Format Inline Types
```ts
type RangeFormatConfig = {
fill?: FillConfig | null;
font?: RangeFontConfig | null;
borders?: RangeBordersConfig;
numberFormat?: string | string[][];
wrapText?: boolean;
horizontalAlignment?:
| "general"
| "left"
| "center"
| "right"
| "fill"
| "justify"
| "centerAcrossSelection"
| "distributed";
verticalAlignment?: "top" | "middle" | "bottom" | "center";
rowHeight?: number; // points
rowHeightPx?: number;
columnWidth?: number; // Excel width units
columnWidthPx?: number;
};
type RangeFontConfig = {
bold?: boolean;
italic?: boolean;
size?: number;
name?: string;
color?: ColorConfig;
};
```
## Sizing
```ts
range.format.rowHeightPx = rowHeightPx;
range.format.columnWidthPx = columnWidthPx;
```
Pixel sizing is the preferred surface for layout-sensitive work. Point row heights and Excel-width column widths are also available through `rowHeight` and `columnWidth`.
## Borders
```ts
range.format.borders = {
preset,
style,
color,
};
```
Use the border preset strings below. Border style strings are Excel/OpenXML-style names such as `"thin"`, `"medium"`, `"thick"`, `"dashed"`, and `"dotted"`.
## Border Inline Type
```ts
type RangeBordersConfig =
| {
preset: "none" | "outside" | "inside" | "all" | "doubleBottom";
style?: string; // common: "thin", "medium", "thick", "dashed", "dotted"
color?: ColorConfig;
}
| {
top?: BorderLineInput;
bottom?: BorderLineInput;
left?: BorderLineInput;
right?: BorderLineInput;
inside?: BorderLineInput;
insideHorizontal?: BorderLineInput;
insideVertical?: BorderLineInput;
diagonalUp?: BorderLineInput;
diagonalDown?: BorderLineInput;
};
type BorderLineInput = {
style?: string;
color?: ColorConfig;
weight?: number;
};
```
@@ -0,0 +1,55 @@
# Worksheet Tables
Use `sheet.tables` to add and edit Excel-style tables.
## Add Table
```ts
const table = sheet.tables.add(rangeAddress, hasHeaders, tableName);
```
## Add Inline Type
```ts
type WorksheetTableAddArgs = {
range: string | Range;
hasHeaders?: boolean;
name?: string;
};
```
## Rows And Values
```ts
table.rows.add(rowIndex, rowValues);
table.getRange().values = tableValues;
```
## Table Style
```ts
table.name = tableName;
table.showTotals = showTotals;
table.style = tableStyleName;
table.styleOptions = tableStyleOptions;
```
## Table Inline Type
```ts
type WorkbookTableStyleOptions = {
showHeaders?: boolean;
showTotals?: boolean;
bandedRows?: boolean;
bandedColumns?: boolean;
firstColumn?: boolean;
lastColumn?: boolean;
};
```
## Delete
```ts
table.delete();
sheet.tables.deleteAll();
```
@@ -0,0 +1,31 @@
## Workbook API
Use `Workbook` to create, edit, recalculate, and export spreadsheet artifacts.
### Quick start
```ts
import { Workbook } from "@oai/artifact-tool";
const workbook = Workbook.create();
const sheet = workbook.worksheets.add("Sheet1");
sheet.getRange("A1").values = [["Hello"]];
workbook.recalculate();
const proto = workbook.toProto();
```
### Workbook lifecycle
- `Workbook.create()` — start a new workbook.
- `Workbook.load(proto)` — hydrate from an existing artifact, edit, then `toProto()` again.
- `workbook.recalculate()` — evaluate formulas.
- `workbook.toProto()` — produce the protobuf-like JSON artifact.
### Worksheets
- `workbook.worksheets.add(name)` — add (or return) a worksheet by name.
- `workbook.worksheets.getItem(name | index)` — fetch by name or index.
- `workbook.worksheets.getActiveWorksheet()` — fetch the active worksheet.
- `workbook.worksheets.count` — number of sheets.