|
1 | 1 | ---
|
2 |
| -title: 'Work with PivotTables in Office Scripts' |
3 |
| -description: 'Learn about the object model for PivotTables in the Office Scripts JavaScript API.' |
4 |
| -ms.date: 10/01/2022 |
| 2 | +title: Work with PivotTables in Office Scripts |
| 3 | +description: Learn about the object model for PivotTables in the Office Scripts JavaScript API. |
| 4 | +ms.date: 09/08/2023 |
5 | 5 | ms.localizationpriority: medium
|
6 | 6 | ---
|
7 | 7 |
|
@@ -74,6 +74,36 @@ Each part of the PivotTable maps to a range. This lets your script get data from
|
74 | 74 |
|
75 | 75 | :::image type="content" source="../images/pivottable-layout-breakdown.png" alt-text="A diagram showing which sections of a PivotTable are returned by the layout's get range functions.":::
|
76 | 76 |
|
| 77 | +### PivotTable total output |
| 78 | + |
| 79 | +The location of the total row is based on the layout. Use [`PivotLayout.getBodyAndTotalRange`](/javascript/api/office-scripts/excelscript/excelscript.pivotlayout#excelscript-excelscript-pivotlayout-getbodyandtotalrange-member(1)) and get the last row of the column to use the data from the PivotTable in your script. |
| 80 | + |
| 81 | +The following sample finds the first PivotTable in the workbook and logs the values in the "Grand Total" cells (as highlighted in green in the image below). |
| 82 | + |
| 83 | +:::image type="content" source="../images/sample-pivottable-grand-total-row.png" alt-text="A PivotTable showing fruit sales with the Grand Total row highlighted green."::: |
| 84 | + |
| 85 | +```TypeScript |
| 86 | +function main(workbook: ExcelScript.Workbook) { |
| 87 | + // Get the first PivotTable in the workbook. |
| 88 | + const pivotTable = workbook.getPivotTables()[0]; |
| 89 | + |
| 90 | + // Get the names of each data column in the PivotTable. |
| 91 | + const pivotColumnLabelRange = pivotTable.getLayout().getColumnLabelRange(); |
| 92 | + |
| 93 | + // Get the range displaying the pivoted data. |
| 94 | + const pivotDataRange = pivotTable.getLayout().getBodyAndTotalRange(); |
| 95 | + |
| 96 | + // Get the range with the "grand totals" for the PivotTable columns. |
| 97 | + const grandTotalRange = pivotDataRange.getLastRow(); |
| 98 | + |
| 99 | + // Print each of the "Grand Totals" to the console. |
| 100 | + grandTotalRange.getValues()[0].forEach((column, columnIndex) => { |
| 101 | + console.log(`Grand total of ${pivotColumnLabelRange.getValues()[0][columnIndex]}: ${grandTotalRange.getValues()[0][columnIndex]}`); |
| 102 | + // Example log: "Grand total of Sum of Crates Sold Wholesale: 11000" |
| 103 | + }); |
| 104 | +} |
| 105 | +``` |
| 106 | + |
77 | 107 | ## Filters and slicers
|
78 | 108 |
|
79 | 109 | There are three ways to filter a PivotTable.
|
|
0 commit comments