I'm working with the gspread
module and recently faced this issue with insert_row()
: by default, this function adds a new row above. The problem with this approach is that "adding row above" will drag the formatting of the row upwards. Similarly, "adding row below" will drag the formatting of the row downwards.
In my spreadsheet I have subsections, each with different formatting and formulas, e.g. the range A1:J15 is one subsection. Then, row 16-17 act as a separator, colored dark grey, and without any information or formulas in them.
I would want to extend the range A1:J15. I thought this would be easy using sheet_instance.insert_row(values=None, index=row_index)
but, as mentioned above, if I set row_index
to 16 to add the new row above, the dark grey separator will now get one new row and I will lose all the formulas in that section for (the new) row 16.
If I set row_index
to 15, I will have the new row's formulas and formatting in place. However, in this case (the new) row 15 will not be in the correct position, since that data must be in the last row of the section, but due to gspread
adding the row above, now the last two rows of data are swapped, which is not correct.
Is there any way to force insert_row()
to add rows downwards? If not, what other options I have to circumvent this problem?
Edit:
I tried using append_rows()
too by setting its table_range
attribute identical to my subsection range, i.e. A1:J15 but with no success:
sheet_instance.append_rows(values=[None]*2, insert_data_option='INSERT_ROWS', table_range='A1:J15')
I managed to solve it. Turns out there is an "Insert empty row/column" request in the Google Sheets API which has an inheritFromBefore
parameter, exactly the one I need. By setting this parameter to True
, I could force that insertion drag formatting from above, i.e. replicate the "insert row below" functionality.
My code is as follows:
body = {
'requests': {
'insertDimension': {
"range": {
"sheetId": sheet_instance.id,
"dimension": "ROWS",
"startIndex": row_idx-1,
"endIndex": row_idx
},
"inheritFromBefore": True
}
}
}
for _ in range(3):
response = service.spreadsheets().batchUpdate(
spreadsheetId=sheet_id,
body=body).execute()
The above code inserts 3 new rows just before the original row_idx
row.