+{"version":"0.3.0","body":"/**\r\n * Creates a pivot table from an existing table with specified row and value aggregations.\r\n * \r\n * @param tableName Name of the source table for the pivot table.\r\n * @param location Where to place the pivot table: \"New sheet\" creates a new worksheet, \"Existing sheet\" places it below the source table unless a sheet name is specified.\r\n * @param rowsColumn Column name to use for pivot table rows.\r\n * @param valuesColumns Array of column names to aggregate in the pivot table values area.\r\n * @param valuesOperation Aggregation function to apply to the values columns.\r\n * @param sheetName The name of the sheet the pivot table should be placed on when location is Existing sheet (defaults to same sheet as table). If location is New sheet, this is the name the new sheet should have.\r\n * @param pivotTableName Optional name for the pivot table (auto-generates if blank or already exists)\r\n */\r\nfunction main(\r\n workbook: ExcelScript.Workbook,\r\n tableName: string,\r\n location: \"New sheet\" | \"Existing sheet\" = \"New sheet\",\r\n rowsColumn: string,\r\n valuesColumns: Array<string>,\r\n valuesOperation: \"Sum\" | \"Count\" | \"Average\" | \"Product\" | \"Max\" | \"Min\" = \"Sum\",\r\n columnsColumn?: string,\r\n sheetName?: string,\r\n pivotTableName?: string\r\n) {\r\n const table = workbook.getTable(tableName);\r\n if (!table) {\r\n throw new Error(`Table '${tableName}' not found.`);\r\n }\r\n\r\n if (table.getRowCount() === 0) {\r\n throw new Error(`Table '${tableName}' has no data.`);\r\n }\r\n\r\n // make sure specified columns exist\r\n const tableCols = table.getColumns().map((col) => col.getName());\r\n if (!tableCols.includes(rowsColumn)) {\r\n throw new Error(`There is no column '${rowsColumn}' in table '${tableName}'.`);\r\n }\r\n else {\r\n valuesColumns.forEach((colName) => {\r\n if (!tableCols.includes(colName)) {\r\n throw new Error(`There is no column '${colName}' in table '${tableName}'.`);\r\n }\r\n });\r\n }\r\n\r\n // validate operation\r\n const operation = ExcelScript.AggregationFunction[valuesOperation.toLowerCase() as keyof typeof ExcelScript.AggregationFunction];\r\n if (!operation) {\r\n throw new Error(`Invalid operation: ${valuesOperation}`);\r\n }\r\n\r\n // get range of where to add pivot table\r\n let locationRange: ExcelScript.Range;\r\n if (location === \"New sheet\") {\r\n locationRange = workbook.addWorksheet(sheetName).getRange(\"A1\");\r\n } else {\r\n let locationReference: ExcelScript.Worksheet;\r\n if (sheetName) {\r\n const sheet = workbook.getWorksheet(sheetName);\r\n if (!sheet) {\r\n throw new Error(`There is no worksheet \"${sheetName}\" in the Excel file.`);\r\n }\r\n\r\n locationReference = sheet;\r\n } else {\r\n locationReference = table.getWorksheet();\r\n }\r\n const lastUsedRow = locationReference.getUsedRange().getLastRow();\r\n // 2 for offset + 1 for 0-based index\r\n console.log(`Destination: '${locationReference.getName()}'!A${lastUsedRow.getRowIndex() + 3}`);\r\n locationRange = lastUsedRow.getCell(0, 0).getOffsetRange(2, 0);\r\n }\r\n\r\n const usedSheetName = locationRange.getWorksheet().getName();\r\n\r\n // get next available pivot table name if provided one is taken or blank\r\n const existingPivotTables = workbook.getPivotTables().map((pvtTbl) => pvtTbl.getName());\r\n if (!pivotTableName || existingPivotTables.includes(pivotTableName)) {\r\n const defaultName = \"PivotTable\";\r\n let i = 1;\r\n const maxAttempts = 100;\r\n while (existingPivotTables.includes(defaultName + i) && i < maxAttempts) {\r\n i++;\r\n }\r\n\r\n if (i >= maxAttempts) {\r\n throw new Error(`Unable to generate unique pivot table name after ${i} attempts`);\r\n }\r\n\r\n pivotTableName = defaultName + i;\r\n }\r\n\r\n const pivotTable = workbook.addPivotTable(pivotTableName, table, locationRange);\r\n\r\n // add rows field to pivot table\r\n pivotTable.addRowHierarchy(pivotTable.getHierarchy(rowsColumn));\r\n\r\n // add columns field to pivot table if it exists\r\n if (columnsColumn) {\r\n pivotTable.addColumnHierarchy(pivotTable.getHierarchy(columnsColumn));\r\n }\r\n\r\n // add values fields to pivot table\r\n valuesColumns.forEach((colName) => {\r\n const valuesField = pivotTable.addDataHierarchy(pivotTable.getHierarchy(colName));\r\n valuesField.setSummarizeBy(operation);\r\n });\r\n\r\n return {\r\n \"message\": \"Successfully created a pivot table.\",\r\n \"createdPivotTableName\": pivotTableName,\r\n \"usedSheetName\": usedSheetName\r\n }\r\n}","description":"Creates a pivot table from an existing table with specified row and value aggregations.","noCodeMetadata":"","parameterInfo":"{\"version\":1,\"originalParameterOrder\":[{\"name\":\"tableName\",\"index\":0},{\"name\":\"location\",\"index\":1},{\"name\":\"rowsColumn\",\"index\":2},{\"name\":\"valuesColumns\",\"index\":3},{\"name\":\"valuesOperation\",\"index\":4},{\"name\":\"columnsColumn?\",\"index\":5},{\"name\":\"sheetName?\",\"index\":6},{\"name\":\"pivotTableName?\",\"index\":7}],\"parameterSchema\":{\"type\":\"object\",\"required\":[\"tableName\",\"location\",\"rowsColumn\",\"valuesColumns\",\"valuesOperation\",\"columnsColumn?\",\"sheetName?\",\"pivotTableName?\"],\"properties\":{\"tableName\":{\"type\":\"string\"},\"location\":{\"type\":\"string\"},\"rowsColumn\":{\"type\":\"string\"},\"valuesColumns\":{\"type\":\"string\"},\"valuesOperation\":{\"type\":\"string\"},\"columnsColumn?\":{\"type\":\"string\"},\"sheetName?\":{\"type\":\"string\"},\"pivotTableName?\":{\"type\":\"string\"}}},\"returnSchema\":{\"type\":\"object\",\"properties\":{}},\"signature\":{\"comment\":\"\",\"parameters\":[{\"name\":\"workbook\",\"comment\":\"\"},{\"name\":\"tableName\",\"comment\":\"\"},{\"name\":\"location\",\"comment\":\"\"},{\"name\":\"rowsColumn\",\"comment\":\"\"},{\"name\":\"valuesColumns\",\"comment\":\"\"},{\"name\":\"valuesOperation\",\"comment\":\"\"},{\"name\":\"columnsColumn?\",\"comment\":\"\"},{\"name\":\"sheetName?\",\"comment\":\"\"},{\"name\":\"pivotTableName?\",\"comment\":\"\"}]}}","apiInfo":"{\"variant\":\"synchronous\",\"variantVersion\":2}"}
0 commit comments