5

I am trying to use Gspread to insert new columns at a location. I found add_cols methods, but it inserts only in the last column of spreadsheet.

There are other methods such as: insert_rows, resize or append_rows but nothing can solve my problem. Did i miss anything? Thank you

Khanh Le
  • 404
  • 4
  • 18

3 Answers3

3

Use the default batch update API for this

spreadsheetId=''
sheetId=''

sht = gc.open_by_key(spreadsheetId)

requests = []

requests.append({
      "insertDimension": {
        "range": {
          "sheetId": sheetId,
          "dimension": "COLUMNS",
          "startIndex": 2,
          "endIndex": 4
        },
        "inheritFromBefore": True
      }
    })

body = {
    'requests': requests
}

sht.batch_update(body)
contributorpw
  • 4,739
  • 5
  • 27
  • 50
1

Not sure if this would help you now but might help someone else. Also, seems Gspread Hasn't added this yet... If you go on the gspread site package - you can add the this to the "models.py" file, I did it righ above the "def insert_row" but realistically you can do it anywhere tbh.

    def insert_col(self,values,index=1,value_input_option='RAW'):
        body = {
            "requests": [
                {
                    "insertDimension": {
                        "range": {
                            "sheetId": self.id,
                            "dimension": "COLUMNS",
                            "startIndex": index - 1,
                            "endIndex": index,
                        }
                    }
                }
            ]
        }
        self.spreadsheet.batch_update(body)

        range_label = absolute_range_name(self.title, 'A%s' % index)

        data = self.spreadsheet.values_update(
            range_label,
            params={'valueInputOption': value_input_option},
            body={'values': [values]},
        )

        return data
0

you can made it

def insert_empty_column(ws: Worksheet):
    ws.insert_cols([None] * 15, col=15, value_input_option='RAW', inherit_from_before=False)   

I create even issue https://github.com/burnash/gspread/issues/1258 but thay say that it's already works