officefileapi-113741-spreadsheet-document-api-examples-group-data-how-to-insert-subtotals-in-a-data-range.md
The example below demonstrates how to use the Worksheet.Subtotal method to automatically create outlines for a sorted range and summarize data in each group using the SUBTOTAL function.
Important
Before subtotaling, make sure that the range you wish to subtotal has column headings in the first row and the data in this range is sorted by a column at each change in which a subtotal row will be inserted.
To insert subtotals, do the following.
CellRange dataRange = worksheet["B3:E23"];
// Specify that subtotals should be calculated for the column "D".
List<int> subtotalColumnsList = new List<int>();
subtotalColumnsList.Add(3);
// Insert subtotals by each change in the column "B" and calculate the SUM fuction for the related rows in the column "D".
worksheet.Subtotal(dataRange, 1, subtotalColumnsList, 9, "Total");
Dim dataRange As CellRange = worksheet("B3:E23")
' Specify that subtotals should be calculated for the column "D".
Dim subtotalColumnsList As New List(Of Integer)()
subtotalColumnsList.Add(3)
' Insert subtotals by each change in the column "B" and calculate the SUM fuction for the related rows in the column "D".
worksheet.Subtotal(dataRange, 1, subtotalColumnsList, 9, "Total")
The image below shows the result (the workbook is opened in Microsoft® Excel®).
See Also