Can Gspread insert new columns at location?
Asked Answered
P

3

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

Prudential answered 5/4, 2017 at 4:28 Comment(2)
No I don't think you're missing anything: gspread.readthedocs.io/en/latest/#main-interface There is no corresponding insert_col method.Halutz
i am sorry, i mean add_cols, i've edited itPrudential
M
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)
Modulate answered 28/1, 2019 at 20:44 Comment(0)
D
2

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
Djokjakarta answered 26/8, 2020 at 21:39 Comment(0)
S
2

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

Stringer answered 2/8, 2023 at 14:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.