Spreadsheets

From bighardperson/computer-science-skills-collection · View interactive version

Spreadsheets is an AI agent skill from the GitHub repository bighardperson/computer-science-skills-collection. Use this skill when a user requests to create, modify, analyze, visualize, or work with spreadsheet files (`.xlsx`, `.xls`, `.csv`, `.tsv`) with formulas, formatting, charts, tables, and recalculation.

How to use this skill

Skill file

Spreadsheets skill

This skill includes guidelines for how to produce a correct, polished 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 guidelines 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

Tools + Contract

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.

Additional Instructions

Read the following templates instructions ONLY when a request relates to any of the following:

Do not load these for other tasks that are unrelated unless the prompt explicitly asks for it.

Source and PDF Extraction

Using artifact_tool APIs (JavaScript)

Required 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 Rules

Conventions

Discovery Policy (Strict)

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

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 = [["Some long description that should cross multiple cells"]];

Known Gotchas (Do Not Repeat)

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

Validation + conditional formatting

const r = sheet.getRange("B2:B20");
r.conditionalFormats.addCellIs({
  operator: "lessThan",
  formula: 0,
  format: { font: { color: "#DC2626" } },
});
r.conditionalFormats.addCustom("=B2<0", { fill: "#FECACA" });
r.conditionalFormats.addColorScale({
  minColor: "#FEE2E2",
  midColor: "#FEF3C7",
  maxColor: "#DCFCE7",
});
r.conditionalFormats.addDataBar({ color: "accent5", gradient: true });

Tables

Charts

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

Sparklines

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

JavaScript example snippet (runnable)

import fs from "node:fs/promises";
import { SpreadsheetFile, Workbook } from "@oai/artifact-tool";

async function quickApiExample() {
  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:E10").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:D10");
  dataRange.format.wrapText = true;
  sheet.showGridLines = false;

  // Format dates properly.
  sheet.getRange("D2:D10").format.numberFormat = "MM/DD/YYYY";

  // Conditional formatting
  sheet.getRange("C2:C10").conditionalFormats.addDataBar({
    color: "#704023",
    gradient: true,
  });
  sheet.getRange("E2:E10").conditionalFormats.add("cellIs", {
    operator: "greaterThan",
    formula: 300,
    format: { font: { color: "#B91C1C" } },
  });
  sheet.conditionalFormattings.add({
    range: "B2:B10",
    rule: {
      type: "expression",
      formula: '=B2="Introvert"',
      format: { fill: "#FCA5A5" },
    },
  });

  // Data validation: Since Personality Type is a dropdown category, add data validation.
  sheet.getRange("B2:B10").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:E10", true, "PeopleTable");
  table.getHeaderRowRange();

  // First column is still wide since we only auto-fit the first row. Expand it manually.
  sheet.getRange("A1:A10").format.columnWidth = 20;

  // Create charts to the right of the table
  sheet.getRange("H1:O1").merge();
  sheet.getRange("H1").values = [["Charts"]];
  sheet.getRange("H1").format = headerFormats;

  // Adding charts
  const chart = sheet.charts.add("bar", {
    from: { row: 1, col: 7 },
    extent: { widthPx: 620, heightPx: 320 },
  });
  chart.title = "Person by Scores";
  chart.hasLegend = true;
  chart.displayBlanksAs = "zero";
  chart.legend.position = "right";
  chart.barOptions.direction = "column";
  chart.barOptions.grouping = "clustered";
  const sheetRef = sheet.name.replaceAll("'", "''");
  const dataEndRow = 4; // Keep chart refs to rows with data only.

  const scoreSeries = chart.series.add("Scores by Person");
  scoreSeries.categoryFormula = `'${sheetRef}'!$A$2:$A$${dataEndRow}`;
  scoreSeries.formula = `'${sheetRef}'!$E$2:$E$${dataEndRow}`;
  scoreSeries.valuesFormatCode = "0";
  chart.setPosition("H2", "O16");

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

  // Chart 2 - Fastest path with defaults
  const chart2 = sheet.charts.add("line", sheet.getRange("B2:C4"));
  chart2.title = "Scores by Personality";
  chart2.setPosition("H20", "O35");

  // 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:E10"),
    targetRange: sheet.getRange("F2:F10"),
    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);
}

await quickApiExample();

Render:

const imageBlob = await workbook.render({
  sheetName: "ExampleSheet",
  autoCrop: "all",
  scale: 1,
  format: "png",
});

Export:

const xlsx = await SpreadsheetFile.exportXlsx(workbook);
await xlsx.save("output/spreadsheet.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.