Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use wrap_strategy in python for google sheets?

I have a python code which uses drive and sheet api to list the files inside of a folder. I have multiple google sheets inside this folder and some of them have spaces in between texts, like the one given in the image. I wanted to change the text wrap to overflow for all the cells i.e sheet object in python using google sheet api. I can see there is a way (wrap_strategy) to set it to overflow_cell, but I don't know how to use it. Can anyone please help in this case?

I can see the documentation in apps script but not using python.

def process_file(file):
    file["name"] = file["name"] + '.' + file["id"] #prefix the file name 
    print(file["name"])
sheet = open_sheet(file['id'])
if sheet is None:
    print("Unable to open sheet: " + file['id'])
    return

The actual result would format all google sheets inside this folder with text formatting as overflow for all the cells

like image 651
Prajakta Yerpude Avatar asked Sep 15 '25 05:09

Prajakta Yerpude


2 Answers

  • You want to set the wrap strategy of a sheet on Spreadsheet.
  • You want to set the wrap strategy of all cells of the sheet as "overflow".
  • You want to achieve this using gspread.

From your question and tag, I understood like above.

In this sample script, it supposes that the wrap strategy of "overflow" is set to all cells of "Sheet1". When batch_update() is used at gspread, the request body is required to be created.

Sample script:

spreadsheetId = "###"  # Please set this
sheetName = "Sheet1"  # Please set this

client = gspread.authorize(credentials)
spreadsheet = client.open_by_key(spreadsheetId)
sheetId = ss.worksheet(sheetName)._properties['sheetId']
body = {
  "requests": [
    {
      "updateCells": {
        "range": {
          "sheetId": sheetId,
          "startRowIndex": 0,
          "startColumnIndex": 0
        },
        "rows": [
          {
            "values": [
              {
                "userEnteredFormat": {
                  "wrapStrategy": "OVERFLOW_CELL"
                }
              }
            ]
          }
        ],
        "fields": "userEnteredFormat.wrapStrategy"
      }
    }
  ]
}
res = spreadsheet.batch_update(body)

Note:

  • This sample script supposes that you have already been able to read and write the Spreadsheet using Sheets API.

References:

  • RepeatCellRequest
  • WrapStrategy
  • batch_update(body)
like image 103
Tanaike Avatar answered Sep 17 '25 18:09

Tanaike


Why not use gspread formatting, it is a simple command:

from gspread_formatting import *

worksheet.format("A1:D10", {"wrapStrategy": "OVERFLOW_CELL"})

In my case I was looking how to set it to WRAP because it was overflow by default...

like image 38
Ecuador Avatar answered Sep 17 '25 18:09

Ecuador