Spreadsheets

From fanfan-de/anybox · View interactive version

Spreadsheets is an AI agent skill from the GitHub repository fanfan-de/anybox. Use this skill when a user requests to create, modify, analyze, visualize, or work with editable Microsoft Excel spreadsheet files (`.xlsx`, `.xls`, `.csv`, `.tsv`) with formulas, formatting, charts, tables, and recalculation.

How to use this skill

Skill file

Excel XLSX Builder skill

This skill includes requirements and guidance for producing a correct, polished Microsoft Excel spreadsheet artifact quickly that completes the user's request. When producing spreadsheets or workbooks, you will be judged on layout, readability, style, adherence to industry norms/conventions and correctness. Follow the requirements below for how to use the APIs effectively and how to verify your output before finalizing work for the user.

For complex, analytical, financial or research involved tasks, you are especially judged on correctness and quality. You need to be professional. For these, always make sure you have a plan for how you're organizing the spreadsheet, and the data or visualizations within each sheet. For business, finance, operations, dashboard, and data-analysis prompts, aim for an output that can compete with a strong analyst-built workbook, not just a functional grid. A good default shape is an executive summary or dashboard first, then source/assumptions, then model/detail sheets. For simpler tasks like a creating template or tracker, or things that do not require research, prioritize doing the spreadsheet build and edits quickly, while ensuring the user's request is fulfilled.

For additional stylistic best practices, follow: style_guidelines.md

Read charts.md when creating or editing substantive charts, dashboards, or chart-ready summaries.

Tools + Contract

Domain Requirements

Read these domain templates only when the request clearly relates to the domain:

Read all templates that clearly apply. Do not load domain templates for unrelated routine, lightweight, or basic formatting/editing tasks unless the user explicitly asks.

Only add Checks sheets for models where correctness depends on linked calculations, source reconciliation, or financial statement/model integrity.

General Rules

Approach for quickly building a new spreadsheet

  1. Setup: import @oai/artifact-tool, create workbook/sheets for new files.
  2. Build quickly: bulk-write headers/data/formulas; then formatting/validation/conditional formatting; add charts/tables only when needed.
  3. Use additional focused calls if helpful for streamed progress.
  4. Near completion: inspect key ranges, scan formula errors, render all the sheets and verify, run a validation pass
  5. Export .xlsx

Making edits on a spreadsheet

If a user asks to edit or add to an existing spreadsheet:

Handling queries and questions

Error Recovery

On first error:

  1. Read error text.
  2. Run one targeted workbook.help("<exact_api>") query only if needed.
  3. Retry with minimal patch (not full rewrite).
  4. Continue from existing workbook state.

Do not loop indefinitely on similar failures.

Quality Guidelines

Completion Criteria

Complete only when:

Verification Rules

Before final response, verify values/formulas and visual quality.

  1. Inspect key ranges:
const check = await workbook.inspect({
  kind: "table",
  range: "Dashboard!A1:H20",
  include: "values,formulas",
  tableMaxRows: 20,
  tableMaxCols: 12,
});
console.log(check.ndjson);

Inspect targeting:

  1. Scan formula errors:
const errors = await workbook.inspect({
  kind: "match",
  searchTerm: "#REF!|#DIV/0!|#VALUE!|#NAME\\?|#N/A",
  options: { useRegex: true, maxResults: 300 },
  summary: "final formula error scan",
});
console.log(errors.ndjson);
  1. Render sheets/ranges to verify visual output (skip if already verified and no style changes):
const blob = await workbook.render({ sheetName: "Sheet1", range: "A1:H20", scale: 2 });

Make sure you do at least one visual pass of all the sheets in the workbook before the final export.

Visual requirements:

  1. Keep verification compact:
  1. Export:
await fs.mkdir(outputDir, { recursive: true });
const output = await SpreadsheetFile.exportXlsx(workbook);
await output.save(`${outputDir}/output.xlsx`);
  1. Finalize immediately after successful export + compact verification.

Source, PDF, and Attachment Processing

Using artifact_tool APIs (JavaScript)

Imports + Startup

Import existing workbook only when needed:

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:

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.

Create new workbook:

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:

await fs.mkdir(outputDir, { recursive: true });
const output = await SpreadsheetFile.exportXlsx(workbook);
await output.save(`${outputDir}/output.xlsx`);

Build Patterns

Conventions

API Discovery

Efficient Formula Lookup

Useful help calls:

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);

Reading existing/imported workbooks

Inspect for workbook understanding

await wb.inspect({
  kind: "workbook,sheet,table",
  maxChars: 6000,
  tableMaxRows: 6,
  tableMaxCols: 6,
  tableMaxCellChars: 80,
});
await wb.inspect({
  kind: "region",
  sheetId: firstSheetName,
  range: "A1:Z30",
  maxChars: 2500,
});

Additional feature-specific notes

Merging cells

For example:

const range = sheet.getRange("I23:N24");
range.merge();
range.values = [["Source note spanning the recommendation panel"]];

Common API Pitfalls

Quick API Surface (High-Value + Common)

Core workbook/file APIs

const previewBytes = new Uint8Array(await preview.arrayBuffer());
await fs.writeFile(`${outputDir}/preview.png`, previewBytes);

Worksheet selection/creation

Worksheet operations

Range values/formulas

Formatting

Data Validation

Conditional formatting

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 };

| "colorScale" | "dataBar" | "iconSet"

| "containsText" | "notContainsText" | "beginsWith" | "endsWith"

| "containsBlanks" | "notContainsBlanks" | "containsErrors" | "notContainsErrors"

| "duplicateValues" | "uniqueValues" | "timePeriod" | "top10" | "aboveAverage";

const grid = sheet.getRange("B2:J10");
grid.conditionalFormats.add("colorScale", {
  criteria: [
    { type: "lowestValue", color: "#2563EB" },
    { type: "percentile", value: 50, color: "#FDE047" },
    { type: "highestValue", color: "#DC2626" },
  ],
});

Tables

Images


### Threaded Comments
Follow this exact API when adding a note or comment:
- Required: First, always first call set_self to create an author `workbook.comments.setSelf({"displayName": "ChatGPT"})`
- 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
- When adding or moving charts, do not cover existing data. Put charts in a reserved rectangle with blank gutter columns/rows around the chart area.
- Fast chart path, no help lookup needed for common line/bar/scatter charts: write a compact helper range with text categories and one column per series, then chart that range.
- If chart data comes from editable/source data, make the helper range formula-backed instead of copying literal values.

sheet.getRange("F4:H7").values = [

["Month", "Revenue", "EBITDA"],

["Jan", 100, 10],

["Feb", 120, 18],

["Mar", 130, 22],

];

const chart = sheet.charts.add("line", sheet.getRange("F4:H7"));

chart.setPosition("J4", "Q20");

chart.title = "Revenue and EBITDA Trend";

chart.hasLegend = true;

chart.xAxis = { axisType: "textAxis" };

chart.yAxis = { numberFormatCode: "$#,##0" };

- Fast chart path from range: `const chart = sheet.charts.add("line", sourceRange)` when the source range already has headers and text x-axis labels.
- Advanced fallback only: avoid manual `chart.series.add(...)` and `chart.legend = {...}` on the first pass unless source-range chart creation does not work (for example, non-continuous data). Use a helper range chart first, then add optional chart styling only if the basic chart renders and exports cleanly.
- If you want to set specific chart props after the helper-range path is not enough: `const chart = sheet.charts.add("bar", chartProps)`, then checkpoint export before adding optional styling.
- If using compat positioning, always set position: `chart.setPosition("F2", "M20")`.
- `sheet.charts.getItemOrNullObject("Chart 1")`, `sheet.charts.deleteAll()`
- To update x/y-axis, prefer compact config assignments such as `chart.xAxis = { axisType: "textAxis", tickLabelInterval: 2 }` and `chart.yAxis = { numberFormatCode: "$#,##0" }`. These help legibility and visibility.
- For month/date x-axes, prefer a chart helper range with text labels such as `Jan 2025` or `2025-01`. Do not rely on date axis number formats alone; rendered previews can show Excel serial numbers.
- Chart types: `"bar" | "line" | "area" | "pie" | "doughnut" | "scatter" | "bubble" | "radar" | "stock" | "treemap" | "sunburst" | "histogram" | "boxWhisker" | "waterfall" | "funnel" | "map"`.

### Sparklines

const group = sheet.sparklineGroups.add({

type,

targetRange,

sourceData,

dateAxisRange,

seriesColor,

negativeColor,

markers,

axis,

lineWeight,

displayEmptyCellsAs,

displayHidden,

});

- Sparkline type is a string. Empty-cell display mode and axis min/max modes are proto enum numbers on the current facade; inspect nearby tests before setting them directly.
- Sparkline Inline Type:

type SparklineConfig = {

type: "line" | "column" | "stacked";

targetRange: Range | string;

sourceData: Range | string;

dateAxisRange?: 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;

manualMin?: number;

manualMax?: number;

rightToLeft?: boolean;

};

- Range Alias: `const group = targetRange.sparklines.add(type, sourceRange, sparklineConfig);`
- Edit And Delete

group.seriesColor = colorConfig;

group.markers = markerConfig;

group.axis = axisConfig;

group.delete();

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`


### JavaScript example snippet (runnable)

import fs from "node:fs/promises";

import { SpreadsheetFile, Workbook } from "@oai/artifact-tool";

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:D1").format = {

fill: "#0F766E",

font: { 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.hasLegend = false;

chart.xAxis = { axisType: "textAxis" };

chart.yAxis = { numberFormatCode: "$#,##0" };

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);

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.