К основному содержанию
промпт GP ChatGPT

pivot — промпт для Claude Code: что делает и как установить

Инструкция по созданию интерактивных сводных таблиц через add_pivot или расчёту агрегаций формулами SUMIFS.

Apache-2.0 ★ 12 746 обновлён 2026-10-29

Установить в Claude Code · Вручную: положить файлы Все способы и платформы ↓
.claude/commands/pivot.md
Открыть на GitHub

Что делает pivot

Промпт задаёт правила работы со сводными отчётами в электронных таблицах. Агент выбирает операцию add_pivot для построения интерактивной сводной таблицы с фильтрами и группировкой или формирует формульную сетку через SUMIFS и COUNTIFS, когда ячейки должны оставаться доступными для дальнейших расчётов.

Для вызова add_pivot первая строка диапазона обязана содержать заполненные неповторяющиеся заголовки. Допускается до восьми уровней строк, одно измерение столбца, до четырёх фильтров страниц и расчёт долей или рангов. Выходная область не должна перекрывать исходные данные, а размер источника ограничен 10 000 строк и 200 столбцами.

Область сводной таблицы после сохранения защищена от ручной правки через set_cell. Если задано измерение столбца, список значений обязан содержать ровно одно поле.

Какие задачи решает

  • построить интерактивную сводную таблицу в Excel
  • сгруппировать показатели по категориям через формулы SUMIFS
  • обновить вычисленные области листа командой refresh_pivot
  • рассчитать доли от общей суммы или промежуточные итоги

Примеры запросов агенту

  • Сделай сводную таблицу по продажам из диапазона A1:D500 с выводом в ячейку F1
  • Построй двумерную таблицу регион-месяц на формулах SUMIFS
  • Обнови данные всех сводных таблиц на листе s1

Как установить pivot

Вручную: положить файлы

.claude/commands/pivot.md

Вопросы о pivot

Как установить pivot в Claude Code?

Сохраните файл промпта по пути .claude/commands/pivot.md.

Чем add_pivot отличается от агрегации формулами?

Команда add_pivot создаёт интерактивный объект Excel с автоитогами, а формульный подход формирует вычисляемую сетку на базе SUMIFS.

Какие ограничения действуют для команды add_pivot?

Исходный диапазон ограничен 10 000 строк и 200 столбцами, а целевая ячейка не должна пересекаться с источником.

Исходный текст

pivot.md · Apache-2.0
# Pivot table guide (pivot)

## When to pivot vs. formula aggregation

- The user asks for a "pivot table", or wants the result interactive in Excel (drag fields, refresh) → **add_pivot** (real pivot table).
- They just want "summarize by dimension" and will keep computing/charting from the summary values → a formula aggregation table also works (see the fallback plan): the result is real cell formulas that stay computable.

## Creating a pivot table (add_pivot)

`{op:"add_pivot", sheetId, sourceRange:"A1:F1000", targetCell:"H1", targetSheetId?, rowFields, columnField?, pageFields?, values:[{field, agg, showDataAs?, baseField?, baseItem?, name?}], name?}`

- **The first row of sourceRange must be headers** (non-empty and mutually unique); rowFields/columnField/values.field all use the header text.
- rowFields: row dimensions, 1–8 (string or array, **outermost first**); with multiple levels, rows group hierarchically and per-level subtotal rows are added automatically. columnField: column dimension (optional, at most 1; **when columnField is given, values may only have 1 entry**).
- values: `{field:"Amount", agg:"sum"|"count"|"average"|"max"|"min"|"product"|"countNums", showDataAs?, baseField?, baseItem?, name?}`, 1–8 entries; a values field cannot also be a row/column/page dimension; `name` overrides the "Sum of Amount" caption.
- showDataAs (value display mode, optional): `"percentOfTotal"` (% of grand total) | `"percentOfRow"` | `"percentOfCol"` (% of row/column total) | `"percentOfParentRow"` | `"percentOfParentCol"` (% of the next level up) | "percentOfParent" (% of the base field's parent-level total; `baseField` names a row/column field) | `"difference"` (value − base item; blank on the base item and totals) | `"percentDiff"` ((value−base)/base) | `"percentOf"` (value/base) | "runTotal" (running total along the base field's items, restarting per outer member / other-axis group) | `"percentOfRunningTotal"` | `"rankAscending"` / `"rankDescending"` (RANK.EQ-style, ties share the smaller rank) | `"index"`; percent modes display with the 0.00% format by default.
- baseField/baseItem (needed by the base-field showDataAs modes): `baseField` must be a row/column dimension header (e.g. a rowFields entry); `baseItem` is a member label of that field, required by difference / percentDiff / percentOf.
- pageFields (report filters, optional, ≤4): header names or `{field, item}`; they render as "Field | (All)" rows above the table (plus a blank row) and a chosen `item` restricts the whole report to matching source rows.
- targetCell: top-left of the output region, **must not overlap the source region** (put it in blank space right of the source, or use targetSheetId to place it on a summary sheet).
- How it takes effect: on apply, aggregated results (including subtotal and Grand Total rows/columns) are written directly to the target cells and are immediately visible; on save, native pivot parts are written (refreshOnLoad), so **the file opens in Excel as a live interactive pivot table**.
- Limits: source region ≤ 10,000 data rows × 200 columns; each row-dimension level ≤ 10,000 distinct members; the same batch cannot also do row/column insertion/deletion or sheet management on the source/target sheet (save first).
- The output region is protected after saving (not directly editable) — don't stack set_cell on top of it.

```json
{
  "op": "add_pivot",
  "sheetId": "s1",
  "sourceRange": "A1:D500",
  "targetCell": "F1",
  "rowFields": ["Region", "Product"],
  "values": [
    { "field": "Sales", "agg": "sum" },
    { "field": "Sales", "agg": "sum", "showDataAs": "percentOfTotal" }
  ],
  "name": "RegionProductSummary"
}
```

## Refreshing existing pivot tables (refresh_pivot)

`{op:"refresh_pivot", sheetId}` — recomputes the data areas of all pivot tables on the sheet and writes them back. Use it after the source data has changed to bring pivot results up to date.

- When **new categories** appear in the source data, the layout grows automatically: new members are appended at the end of their level (with new subtotal rows for multi-level layouts) and the output region expands — but the area the growth occupies must be empty, otherwise it errors and asks you to clear it first.
- Cases that still fail with explicit errors: renamed headers / moved data sources, calculated fields, grouped fields, value filters, and growth of compact (non-tabular) layouts. Other edge cases are in the data guide's "Pivot tables" section.

## Fallback plan: formula aggregation table (for irregular data or when live formulas are needed)

Compute the summary grid directly with `SUMIFS`/`COUNTIFS`/`AVERAGEIFS`:

**Single-dimension summary** (sales by region):

```json
[
  { "op": "set_range", "sheetId": "s2", "range": "A1:B1", "values": [["Region", "Sales"]] },
  {
    "op": "set_range",
    "sheetId": "s2",
    "range": "A2:A5",
    "values": [["East"], ["South"], ["North"], ["West"]]
  },
  {
    "op": "set_formula",
    "sheetId": "s2",
    "address": "B2",
    "formula": "=SUMIFS(Sheet1!$C:$C,Sheet1!$A:$A,A2)"
  }
]
```

(Fill the B2 formula down to B5; point the criteria ranges at the source table's region/amount columns.)

**Two-dimension cross-tab** (region × month): row headers hold regions, column headers hold months, and each intersection uses a double-criteria `=SUMIFS(src!amount, src!region, $rowHeader, src!month, colHeader$)` (note the `$` locking directions for filling).

**Deduplicating dimension values**: when the source's dimension values are unknown, first `read_range` the source column, write the deduplicated dimension values into the row/column headers in your proposal, then attach the SUMIFS.

## Companion steps

- Once the summary table is computed, add a chart per the `charts` guide (category comparison → column, share → pie).
- Apply `financial-formatting` currency formats to amount columns.
- For formula aggregation tables, the total row uses `=SUM(...)`, bold + light gray fill (add_pivot ships its own Grand Total).

© genspark-ai · Apache-2.0 · genspark-ai/genoffice

Похожие промпты

Все промпты по теме «Документы и офис» →
spreadsheet-formula-helper composio-community Скилл spreadsheet-formula-helper помогает составлять и отлаживать формулы для Excel и Google Таблиц. Пригодится при переносе расчётов между диалектами и обработке пустых строк. CX Codex +1 3установок excel-formula-generator Jeremy Longshore Скилл excel-formula-generator создаёт формулы и конфигурации для электронных таблиц в процессах автоматизации. Включается при запросах о формулах и операциях в Excel. CX Codex +1 2установок syncfusion-react-pivot-table Syncfusion Inc Скилл syncfusion-react-pivot-table помогает собирать и настраивать PivotView в React: данные, группировку, фильтры, агрегации, экспорт и pivot charts. CX Codex +1 740установок excel-mcp Stefan Brönner Управляет локальным Excel через GitHub Copilot: строит таблицы, обновляет Power Query, правит формулы и запускает VBA прямо в открытом окне приложения. ★ 2звёзд репо excel-cli Stefan Brönner Агент создаёт и редактирует книги Microsoft Excel — формулы, Power Query, сводные таблицы, диаграммы и VBA — запуская команды excelcli в терминале. ★ 2звёзд репо xlsx appautomaton Скилл xlsx для Claude Code и Codex: создание, правка и пересчёт книг Excel с живыми формулами, форматированием и диаграммами. Агент выдаёт или изменяет файлы таблиц с проверкой целостности через LibreOffice. CX Codex +1 1 300установок

Из того же набора65

Весь набор →
policy-compliance Скилл policy-compliance генерирует политики конфиденциальности и внутренние регламенты с чеклистами соответствия в Word и Excel. Не юридическая консультация — требует проверки юристом. CX Codex +1 ★ 12 746звёзд репо nda-drafter Скилл nda-drafter составляет односторонние и взаимные соглашения о конфиденциальности в формате Word с пояснениями к статьям и оценкой рисков. CX Codex +1 ★ 12 746звёзд репо labor-contract Скилл labor-contract для Claude Code готовит трудовой договор или offer letter в Word и добавляет чек-лист подписания. Создаёт документы для найма при разных форматах занятости. CX Codex +1 ★ 12 746звёзд репо data Промпт data описывает для Claude операции над импортированными xlsx: ссылки, автофильтр, условное форматирование, проверки ввода, заметки и сводные таблицы. С ним агент правит книгу командами, а не наугад. GP ChatGPT ★ 12 746звёзд репо deck Промпт deck помогает Claude Code менять параметры всей презентации: размер слайдов, тему, колонтитулы, текст и разделы. При неоднозначной задаче он просит уточнить объём изменений. GP ChatGPT ★ 12 746звёзд репо table Промпт table объясняет агенту, когда в Excel-файле ставить настоящую таблицу Excel, а когда сымитировать её вид обычным диапазоном. GP ChatGPT ★ 12 746звёзд репо charts Промпт charts для Claude Code создаёт и редактирует диаграммы в таблицах. Он помогает выбрать тип графика и задать диапазон данных. GP ChatGPT ★ 12 746звёзд репо table Промпт table для Claude Code редактирует таблицы в презентации: меняет ячейки, размеры, объединения и оформление. Запускается по просьбе изменить существующую таблицу. GP ChatGPT ★ 12 746звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой