I'm looking for a way to create a group of rows via the Google Sheets API - is there a way to do this? I can't see to find an API that will do this, but it seems like it should be a fairly common formatting need.
This feature is supported in the UI by selecting a set of rows, right clicking and the option pops up to create a group, see the screenshot linked below. I'm just looking for a way to do that via an API.
Select the rows or columns that you want to group. You can do this easily by dragging through them. Then, right-click and choose the Group option for the rows or columns you selected.
The Google Sheets API lets you read, write, and format Google Sheets data with your preferred programming language, including Java, JavaScript, and Python.
Use this --> Range.shiftColumnGroupDepth
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
var range = sheet.getActiveRange();
// The column grouping depth is increased by 1.
range.shiftColumnGroupDepth(1);
// The column grouping depth is decreased by 1.
range.shiftColumnGroupDepth(-1);
You can accomplish this through version 4 of the Google Sheets API.
You will need to submit an HTTP POST to this endpoint:
https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}:batchUpdate
You will need to pass a valid JSON request. I created a simple spreadsheet with some rows to group and used this JSON as a test to group rows 14-17:
{
"requests": [
{
"addDimensionGroup": {
"range": {
"dimension": "ROWS",
"sheetId": 0,
"startIndex": 14,
"endIndex": 17
}
}
}
]
}
Note that the startIndex is the row (or column) number that everything will fold into and will remain visible even if you collapse the group, while endIndex is the last element of the group which will remain hidden when the group is collapsed.
The documentation for this is here. If your window is wide enough it will show a "Try this API" pane on the right side. You can enter the spreadsheetId of your sheet and build up the JSON request body and test it to see it work directly on a sheet - if you have it open in another window you should see the update happen almost immediate after you click the "Execute" button.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With