问题
I didn't see anything in the documentation that would make me think this is a supported function. I'm writing to several sheets and visually it's difficult to see all the data without highlighting all the columns and autosizing with my mouse. I'd rather not have to do that everytime I run my script.
Is there a way to do this programmatically with app scripts? I saw the option to setColumnWidth, but how do I know how wide to set my columns when my text could vary from column to column.
==thanks for any help.
回答1:
autoResizeColumn(columnPosition)
See the API for more details
回答2:
There is now a new method called autoResizeColumn(columnPosition)
var s = SpreadsheetApp.getActive().getActiveSheet();
s.autoResizeColumn(6);
Autosizes the 6th column (a.k.a column "F").
See this stackoverflow answer https://stackoverflow.com/a/29930315/8458041
There's also a way to do multiple columns at once: autoResizeColumns(startColumn, numColumns)
var s = SpreadsheetApp.getActive().getActiveSheet();
s.autoResizeColumns(6, 3);
Autosizes columns F, G, and H.
The corresponding autosizing method for multiple rows is autoResizeRows(startRow, numRows)
s.autoResizeRows(6, 3);
Autosizes rows 6, 7, and 8
There is no corresponding single-row autosizing method (yet?); to autosize a single row, specify 1 for the number of rows
s.autoResizeRows(6, 1);
Autosizes only row 6
回答3:
Now there is no ability to auto-size spreadsheet columns widths from a GAS. There is a topic in the issue tracker about it. Please star this topic to demonstrate Google that many people require this feature.
回答4:
I found this to work when trying to iterate through a specified number of columns and autosizing based on the width of the text in the column:
for (var i = 1; i < 9; i ++){ sheet.autoResizeColumn(i);}
回答5:
If you disable wrapping on the cells in your range you can achieve the desired affect.
Here's a snippet that worked for me:
var dataRange = sheet.getRange(1,1,data.length,headers.length);
dataRange.setValues(data);
dataRange.setWrap(false);
Goolge Apps Documentation: Range.setWrap
来源:https://stackoverflow.com/questions/12381875/autosize-spreadsheet-columns