Khanh Le
Khanh Le

Reputation: 414

Can Gspread insert new columns at location?

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

Upvotes: 5

Views: 6285

Answers (3)

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

Upvotes: 2

Alfonzo Sanfilippo
Alfonzo Sanfilippo

Reputation: 91

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

Upvotes: 2

oshliaer
oshliaer

Reputation: 4979

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)

Upvotes: 3

Related Questions