import type { PivotChartOptions } from "./chart/types.js"; import type { Table } from "./table.js"; /** * Interface representing the source data abstraction for pivot tables. * This allows both Worksheet and Table to be used as pivot table data sources. */ export interface PivotTableSource { /** Name of the worksheet containing the source data (used in pivotCacheDefinition) */ name: string; /** * Name of the source Table (e.g., "SalesData"). * When present, pivotCacheDefinition uses `` instead of ref+sheet. */ tableName?: string; /** Get row values by 1-indexed row number */ getRow(rowNumber: number): { values: unknown[]; }; /** Get column values by 1-indexed column number */ getColumn(columnNumber: number): { values: unknown[]; }; /** Get all sheet values as a sparse 2D array */ getSheetValues(): unknown[][]; /** Dimensions with short range reference (e.g., "A1:E10") */ dimensions: { shortRange: string; }; } /** * A value field specification with optional per-field metric override. * Use this instead of a plain string when you need different aggregation * metrics for individual value fields. * * @example * ```ts * values: [ * { name: "Sales", metric: "sum" }, * { name: "Quantity", metric: "count" }, * { name: "Price", metric: "average" }, * ] * ``` */ export interface PivotTableValue { /** Column name to aggregate */ name: string; /** * Aggregation metric for this specific value field. * Overrides the table-wide `metric` when specified. * @default inherited from PivotTableModel.metric (which defaults to 'sum') */ metric?: PivotTableSubtotal; } /** * Model for creating a new pivot table. * Pass this to worksheet.addPivotTable() to create a pivot table. */ export interface PivotTableModel { /** * Source worksheet for the pivot table data. * Either sourceSheet or sourceTable must be provided (mutually exclusive). */ sourceSheet?: PivotTableSource; /** * Source table for the pivot table data. * Either sourceSheet or sourceTable must be provided (mutually exclusive). * The table must have headerRow=true and contain at least one data row. */ sourceTable?: Table; /** Column names to use as row fields in the pivot table */ rows: string[]; /** * Column names to use as column fields in the pivot table. * If omitted or empty, Excel will use "Values" as the column field. * When multiple values are specified alongside columns, the synthetic * "∑Values" pseudo-field is appended to the column axis automatically. * @default [] */ columns?: string[]; /** * Column names (or value field specifications) to aggregate in the pivot table. * Each entry can be a plain string (column name) or a {@link PivotTableValue} * object with a per-field metric override. * * @example * ```ts * // Simple: all values use the table-wide metric * values: ["Sales", "Quantity"] * * // Per-value metrics * values: [ * { name: "Sales", metric: "sum" }, * { name: "Quantity", metric: "count" }, * { name: "Price", metric: "average" }, * ] * * // Mixed: plain strings inherit table-wide metric * values: ["Sales", { name: "Quantity", metric: "count" }] * ``` */ values: (string | PivotTableValue)[]; /** * Column names to use as page fields (report filters) in the pivot table. * Page fields appear as dropdown filters above the pivot table. * @default [] */ pages?: string[]; /** * Default aggregation metric for all value fields. * Individual value fields can override this via {@link PivotTableValue.metric}. * @default 'sum' */ metric?: PivotTableSubtotal; /** * Controls whether pivot table style overrides worksheet column widths. * - '0': Preserve worksheet column widths (useful for custom sizing) * - '1': Apply pivot table style width/height (default Excel behavior) * @default '1' */ applyWidthHeightFormats?: "0" | "1"; /** * Top-left cell anchor for the pivot table, e.g. `"A3"` or `"E5"`. * * Specifies where the pivot's displayed block begins. When page filters are * present they occupy rows from the anchor downward, followed by a blank * separator row and then the pivot body (header + data). The library sizes * the initial placeholder range automatically — when Excel refreshes the * pivot cache it expands the pivot from this anchor to its full size. * * When multiple pivot tables share a worksheet, each must be given a distinct * anchor with enough vertical or horizontal room between them so the expanded * pivots do not overlap. Excel reports "there's already a PivotTable there" * when refreshing two overlapping pivots, so this option is required for * dashboards that host several pivots on one sheet. * * Accepts a single-cell address (`"A3"`). A range reference (`"A3:C5"`) is * also tolerated — only the top-left cell is used; the range extent is * recomputed from the pivot's field layout. * * @default `"A3"` (row 3 of column A) */ ref?: string; } /** Allowed element types within CacheField.sharedItems */ export type SharedItemValue = string | number | boolean | Date | PivotErrorValue | null; /** * Wrapper for OOXML error values in sharedItems (e.g. ``). * Distinguishes error strings from regular strings so they roundtrip as `` not ``. */ export declare class PivotErrorValue { /** The error code without the leading '#' (e.g. "REF!", "VALUE!", "N/A") */ readonly code: string; constructor(code: string); /** Returns the display form with '#' prefix, e.g. "#REF!" */ toString(): string; } /** * Represents a cache field in a pivot table. * Cache fields store unique values from source columns for row/column grouping. */ export interface CacheField { /** Name of the field (column header from source) */ name: string; /** Unique values for row/column fields, null for value fields */ sharedItems: SharedItemValue[] | null; /** Whether the field contains numeric values (raw attribute string for roundtrip: "0" or "1") */ containsNumber?: string; /** Whether the field contains only integer values (raw attribute string for roundtrip: "0" or "1") */ containsInteger?: string; /** Minimum value for numeric fields */ minValue?: number; /** Maximum value for numeric fields */ maxValue?: number; /** Number format ID (preserved on roundtrip, defaults to "0") */ numFmtId?: string; /** Original containsSemiMixedTypes attribute from loaded file */ containsSemiMixedTypes?: string; /** Original containsNonDate attribute from loaded file */ containsNonDate?: string; /** Original containsString attribute from loaded file */ containsString?: string; /** Original containsBlank attribute from loaded file */ containsBlank?: string; /** Original containsDate attribute from loaded file */ containsDate?: string; /** Original containsMixedTypes attribute from loaded file */ containsMixedTypes?: string; /** Flag indicating this cache field was loaded from file */ isLoaded?: boolean; /** Preserved raw XML for roundtrip (loaded models only) */ fieldGroupXml?: string; /** Bag of additional cacheField attributes not individually modeled (for roundtrip preservation) */ extraAttrs?: Record; } /** Aggregation function types for pivot table data fields */ export type PivotTableSubtotal = "sum" | "count" | "average" | "max" | "min" | "product" | "countNums" | "stdDev" | "stdDevP" | "var" | "varP"; /** Map from PivotTableSubtotal to its Excel display name prefix */ export declare const METRIC_DISPLAY_NAMES: Readonly>; /** Set of all valid PivotTableSubtotal values (for runtime validation) */ export declare const VALID_SUBTOTALS: ReadonlySet; /** * Data field configuration for pivot table aggregation. * Defines how values are aggregated in the pivot table. */ export interface DataField { /** Display name for the data field (e.g., "Sum of Sales") */ name: string; /** Index of the source field in cacheFields */ fld: number; /** Base field index for calculated fields */ baseField?: number; /** Base item index for calculated fields */ baseItem?: number; /** Aggregation function (default: 'sum') */ subtotal?: PivotTableSubtotal; /** Number format ID (preserved on roundtrip for currency/date formatting) */ numFmtId?: number; } /** * A pivot table chart format entry used by pivot charts. */ export interface PivotTableChartFormat { /** Chart index within the pivot chart formatting collection. */ chart: number; /** Format ID referenced by c:pivotSource/c:fmtId. */ format: number; /** Whether this format applies to a series. */ series?: boolean; /** Preserved or generated pivotArea XML. */ pivotAreaXml?: string; } /** * Internal pivot table representation used by the library. * This is the processed model after calling makePivotTable(). */ export interface PivotTable { /** Pivot table display name, defaults to `PivotTable${tableNumber}` for new tables. */ name?: string; /** Worksheet containing the pivot table. */ worksheetName?: string; /** Source data adapter (always present for new pivot tables) */ source?: PivotTableSource; /** Field indices for row fields */ rows: number[]; /** Field indices for column fields */ columns: number[]; /** Field indices for value fields */ values: number[]; /** Field indices for page fields (report filters) */ pages?: number[]; /** Default aggregation metric */ metric: PivotTableSubtotal; /** Per-value metric overrides (parallel to `values` array). Falls back to `metric`. */ valueMetrics: PivotTableSubtotal[]; /** Cache fields with shared items */ cacheFields: CacheField[]; /** Cache ID for linking to pivot cache */ cacheId: string; /** Width/height format setting */ applyWidthHeightFormats: "0" | "1"; /** * Top-left cell anchor for the pivot block (e.g. `"A3"`). * When present, overrides the default `A{3+pageOffset}` anchor used by the * writer. The anchor represents the cell where the pivot's displayed area * starts (page filters if any, followed by a blank row, followed by the * pivot body). */ ref?: string; /** 1-indexed table number for file naming (pivotTable1.xml, pivotTable2.xml, etc.) */ tableNumber: number; /** Workbook relationship ID, assigned during write by addWorkbookRels() */ rId?: string; /** Flag indicating this pivot table was loaded from file (not newly created) */ isLoaded?: boolean; /** Data fields for loaded pivot tables */ dataFields?: DataField[]; /** Cache definition for loaded pivot tables */ cacheDefinition?: ParsedCacheDefinition; /** Cache records for loaded pivot tables */ cacheRecords?: ParsedCacheRecords; /** Root chartFormat attribute used by pivot charts. */ chartFormat?: number; /** Chart format entries used by pivot charts. */ chartFormats?: PivotTableChartFormat[]; /** Structured pivot chart metadata attached by addPivotChart/addPivotChartsheet. */ pivotChartOptions?: PivotChartOptions; } /** * Parsed cache definition from loaded pivot table files. */ export interface ParsedCacheDefinition { sourceRef?: string; sourceSheet?: string; /** Source table name (name style - references a named Table) */ sourceTableName?: string; /** Cache source type (default "worksheet") */ cacheSourceType?: string; cacheFields: CacheField[]; recordCount?: number; rId?: string; /** Additional attributes to preserve */ refreshOnLoad?: string; createdVersion?: string; refreshedVersion?: string; minRefreshableVersion?: string; isLoaded?: boolean; backgroundQuery?: string; supportSubquery?: string; supportAdvancedDrill?: string; /** Bag of additional root attributes not individually modeled (for roundtrip) */ extraRootAttrs?: Record; /** worksheetSource r:id attribute (for external connections) */ worksheetSourceRId?: string; extLstXml?: string; /** Preserved unknown child elements XML for roundtrip (e.g. calculatedItems, cacheHierarchies) */ unknownElementsXml?: string; /** Preserved raw XML for non-worksheetSource children inside (e.g. ) */ cacheSourceXml?: string; } /** Allowed element types within cache record values */ export type RecordValue = { type: "x"; value: number; } | { type: "n"; value: number; } | { type: "s"; value: string; } | { type: "b"; value: boolean; } | { type: "m"; } | { type: "d"; value: Date; } | { type: "e"; value: string; }; /** * Parsed cache records from loaded pivot table files. */ export interface ParsedCacheRecords { records: RecordValue[][]; count: number; isLoaded?: boolean; /** Extra root attributes beyond xmlns/xmlns:r/count (for roundtrip preservation) */ extraRootAttrs?: Record; } declare function makePivotTable(worksheet: { workbook: { pivotTables: PivotTable[]; }; name: string; }, model: PivotTableModel): PivotTable; export { makePivotTable };