Using Google Sheets API: Can I automatically adjust column width?

Hey everyone, I’m trying to figure out if there’s a way to make columns automatically fit their content in Google Sheets using their API. I’ve been looking around but I’m kind of stuck. The only thing I found was something called DimensionProperties, but that needs me to set an exact pixel value. That’s not really what I’m after.

I’m hoping there’s a simpler way to do this, like how you can double-click a column border in the actual Sheets app to make it fit. Does anyone know if this is possible with the API? Or am I out of luck?

If it helps, here’s a basic example of what I’m trying to do:

from googleapiclient.discovery import build

sheet = build('sheets', 'v4').spreadsheets()
sheet_id = 'your_sheet_id_here'

request = sheet.batchUpdate(spreadsheetId=sheet_id, body={
    'requests': [{
        'autoResizeDimensions': {
            'dimensions': {
                'sheetId': 0,
                'dimension': 'COLUMNS',
                'startIndex': 0,
                'endIndex': 5
            }
        }
    }]
})

response = request.execute()

But this doesn’t work. Any ideas?

sorry mate, i’ve been struggling with this too. the api’s kinda limited for auto-resizing. you could try looping through cells to find the longest content and estimate width, but it’s not perfect. might be easier to just set a fixed width that works most of the time. good luck!

I’ve encountered this issue before, and there isn’t a direct equivalent to the double-click auto-resize feature in the Sheets API. A viable workaround is to calculate the necessary width manually. You can begin by fetching the data for the target columns and then determining the width required by identifying the longest content. Once you have an estimate based on content length and perceived font size, you can use the updateDimensionProperties request to set the column width. This method isn’t perfect and may need adjustments based on specific content or styling.

I’ve grappled with this exact problem in my projects. Unfortunately, there’s no direct API equivalent for the double-click auto-resize we’re used to in the UI. What I’ve found to work reasonably well is a two-step approach:

First, I fetch the data for the columns I want to resize. Then, I write a custom function to estimate the width needed based on the content length, font size, and any formatting applied. It’s not perfect, but it gets you pretty close.

Once I have my estimated widths, I use the updateDimensionProperties request to set them. It takes some trial and error to get it right, but it’s the best solution I’ve found so far.

If you’re dealing with a lot of columns or frequently changing data, you might want to consider running this as a scheduled job to keep things tidy. Just be mindful of your API quota if you’re doing this frequently.