Kanchan
Kanchan

Reputation: 1

How to display the values in columns in Google app script

I got the output as below (row wise):

one
two
three

But I would like to display the value as below (column wise, single value in each cell):

one two three

Can any one please tell me how can I achieve this using getRange function in Google app script ?

Thanks.

Upvotes: 0

Views: 2730

Answers (2)

Jason Allshorn
Jason Allshorn

Reputation: 1625

Not sure if this is helpful. Have you heard about appendRow()? This will add your array to the last row of the sheet.

function append() {
 var arr = ["a","b","c"]
 var ss = SpreadsheetApp.getActiveSpreadsheet();
 var sheet = ss.getSheetByName('Entities')
 sheet.appendRow(arr)

}

Upvotes: 0

Vytautas
Vytautas

Reputation: 2286

Unless you are setting only 1 value, I recommend using getRange(startRow, startCol, numRows, numCols) together with Range class methods getValues() and setValues().

getValues() produces a 2d array which you can access with indexes (let's use integer variables row and col in our example) data[row][col]

So let's say you wish to set one, two, three to column A, B and C in row 1, then you simply have to do

var targetRange = SpreadsheetApp.getActiveSheet().getRange(1, 1, 1, 3)
var data = [['One', 'Two', 'Three']]
targetRamge.setValues(data)

Now let's say I want to write One, Two and Three into Column A over rows 1 2 and 3 then it is only slightly different:

var targetRange = SpreadsheetApp.getActiveSheet().getRange(1, 1, 3, 1) //we now get 1 column, but 3 rows
var data = [['One'], ['Two'], ['Three']] //Each array inside of the main array is a new row
targetRamge.setValues(data)

And there you have it. Simply manipulate the data as a 2D array all the time and use .getValues() and .setValues() with a range that uses multiple rows and/or columns.

Upvotes: 1

Related Questions