Append an array in gSheets? - javascript

Firstly I am very inexperienced here so apologies if this is obvious.
I have an array of data that updates automatically and I wish to copy this data out so I have an archive of it.
I have managed to find the following script which works for what I want:
function saveInstaPostData() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("xxx");
var data0 = sheet.getRange("xxx!A2:AQ21").getValue();
var data1 = sheet.getRange("xxx!B2").getValue();
var data2 = sheet.getRange("xxx!C2").getValue();
var data3 = sheet.getRange("xxx!D2").getValue();
sheet.appendRow([data1,data2,data3,...]);
}
However I have a range of 860 cells, so doing it one by one isn't too feasible.
Reading up on the appendRow method I realise that it (seems) to only be able to append one row at a time. I only have 20 rows so this should still be doable.
I then tried using
function saveInstaPostData() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Insta faction post data");
var values = sheet.getSheetValues(2, 1, 1, 43);
sheet.appendRow([values]);
However this outputs the following in the first cell of the new row: [Ljava.lang.Object;#247f2c9a
This seems to be the array I'm trying to append (java: what is this: [Ljava.lang.Object;?) however I can't get it to work!
[I have also tried using
function saveInstaPostData() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Insta faction post data");
var range = sheet.getRange(2,1,20,43);
var values = range.getValues();
sheet.appendRow([values]);
This outputs ' Range ' in the first cell of the new row.
]
Any pointers would be really appreciated,
Thanks,

On your example, you try to append a tri dimensionnal array:
var values = sheet.getSheetValues(2, 1, 1, 43);
or
var range = sheet.getRange(2,1,20,43);
var values = range.getValues();
Your "values" variable contains a bi dimensionnal array, that you've put in a mono dimensionnal array:
sheet.appendRow([values]); // [values] put bi dimensionnal array in a mono dimensionnal array
To append your data, you need to append each row of your array, one after a other like :
for(var i=0; i<values.length;i++){
sheet.appendRow(values[i]);
}

Related

Google Script GetRange with Filter based on values in a column AND select only certain columns

I have a dataset of 35 columns and 300 rows. I want to get the range that contains rows only for certain values in column 30 (names). The name for which to filter the data is based on the report file cell B6 in the report sheet that is active. So far I tried this:
var report = SpreadsheetApp.getActiveSpreadsheet();
var tsheet = report.getSheetByName("Transactions");
var areport = SpreadsheetApp.getActiveSheet();
var agent = areport.getRange('B6').getValues();
var criteria = SpreadsheetApp.newFilterCriteria().whenTextEqualTo(agent).build();
var trange = tsheet.getRange().createFilter().setColumnFilterCriteria(30, criteria); // ERROR
var tdata = trange.getValues();
I receive an error Exception: The parameters () don't match the method signature for SpreadsheetApp.Sheet.getRange.
The second part, I only want to get several columns, 5,6,7, 13, 15. I can't create another filter with the Spreadsheet app, so is the only way to make an array and filter out the needed data from there? I'm just trying to think ahead and reduce the amount of calculations.
Try with filter():
var report = SpreadsheetApp.getActiveSpreadsheet();
var tsheet = report.getSheetByName("Transactions");
var areport = SpreadsheetApp.getActiveSheet();
var agent = areport.getRange('B6').getValue();
var data = tsheet.getRange('A1:AI300').getValues();
var tdata = data.filter(function (row) {
return row[29] == agent && row[5] == 'Closed' ; // starts from 0, column A is 0.
});
To select particular columns from tdata do:
var cr_data = getCols(tdata,[5,6,7, 13, 15]);
where getCols() is defined as follows:
function getCols(arr,cols) {
return arr.map(row =>
row.filter((_,i) => cols.includes(++i)))
}
and finally you can copy cr_data to a particular place/sheet like that:
sheet.getRange(1,1,cr_data.length,cr_data[0].length).setValues(cr_data);
Regarding the second part of your question I would like to redirect you to this post:
Best method to extract selected columns from 2d array in apps script

How to merge multiple 2d arrays with different lenghts in one big array to display it in google spreadsheets?

I am working with different 2d arrays (rows and columns, google app script). For instance (r = row, c = column):
var array1 =
[[r1c1, r1c2, r1c3],
[r2c1, r2,c2, r2c2]]
var array2 =
[[r1c4, r1c5],
[r2c4, r2c5],
[r3c4, r3c5]]
and I want to have it like that:
var array1and2 =
[[r1c1, r1c2, r1c3, r1c4, r1c5],
[r2c1, r2c2, r2c3, r2c4, r2c5],
[empty, empty, empty, r3c4, r4c5]
]
It doesn't have to be empty but as already said I want to display it in google spreadsheets. The second array should be in the first empty row and column next to the first array.
I hope it is understandable and thank you very much for you help!
Somethink like this you can do:
var array2 = [['r1c4', 'r1c5'],
['r2c4', 'r2c5'],
['r3c4', 'r3c5']];
var array1 = [['r1c1', 'r1c2', 'r1c3'],
['r2c1', 'r2,c2', 'r2c2']];
var result = array2.map((elem, i)=>[...(array1[i] || new Array(array1[0].length).fill('empty')), ...elem]);
console.log(result);
I'm reading your question as being about not just how to create an amalgamated array but actually to manipulate the data in situ, so I'd approach it something like this (assuming that array 1 lives on sheet1 and array 2 lives on sheet2:
function translateArray(){
var sh = SpreadsheetApp.getActiveSpreadsheet();
var ss = sh.getSheetByName("Sheet1");
var os = sh.getSheetByName("Sheet2");
var range1 = ss.getRange("A1:C2");//2 rows 3 columns
var range1Width = range1.getValues()[0].length;//checks length of first row - the width
var range2 = os.getRange("A1:B3");//3 rows 2 columns
var data = range2.getValues();
ss.getRange(1,range1Width,data.length, data[0].length).setValues(data);
}
This code copies the data in sheet2 to sheet 1 alongside it.
use [1] instead of [0] in range1Width if you have header data wider than the real data.
A less orthodox approach:
function merge2Arrays() {
var array1 = [['r1c1', 'r1c2', 'r1c3'],['r2c1', 'r2,c2', 'r2c3']];
var array2 = [['r1c4', 'r1c5'],['r2c4', 'r2c5'],['r3c4', 'r3c5']];
const ss=SpreadsheetApp.getActive();
const sh=ss.insertSheet('xxxxx');
sh.getRange(1,1,array1.length,array1[0].length).setValues(array1);
sh.getRange(1,array1[0].length+1,array2.length,array2[0].length).setValues(array2);
const a=sh.getDataRange().getValues();
ss.deleteSheet(sh);
ret a;
}
function merge3Arrays() {
var array1 = [['r1c1', 'r1c2', 'r1c3'],['r2c1', 'r2,c2', 'r2c3']];
var array2 = [['r1c4', 'r1c5'],['r2c4', 'r2c5'],['r3c4', 'r3c5']];
var array3 = [["r1C6"],["r2c6"],["r3c6"],["r4c6"],["r5c6"],["r6c6"]];
const ss=SpreadsheetApp.getActive();
const sh=ss.insertSheet('xxxxx');
sh.getRange(1,1,array1.length,array1[0].length).setValues(array1);
sh.getRange(1,array1[0].length+1,array2.length,array2[0].length).setValues(array2);
sh.getRange(1,array1[0].length + array2[0].length + 1,array3.length,array3[0].length).setValues(array3);
const a=sh.getDataRange().getValues();
ss.deleteSheet(sh);
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(JSON.stringify(a)), "Display Array");
}

Google Script concat severaly arrays of arrays

I am struggling with the following task: I have an folder with 20 spreadsheets that have all a datatable with the same format (same columns). I want to loop through all of them, collect the data, combine it to one big array and display it on a spreadsheet.
However, I am struggling to combine the arrays. In the first step I load the column headers from the final sheet. Afterwards I loop through all files (I have a table with the sheets ID stored in the array aFiles) but I cannot combine the arrays. I tried it with aData.concat but it didn't do anything.
function getInformation(){
var ssZ = SpreadsheetApp.getActiveSpreadsheet();
var sZu = ssZ.getSheetByName("Meldeeinheiten");
var aFiles = sZu.getDataRange().getValues();
var sDa = ssZ.getSheetByName("Data_komplett")
var aData = sDa.getRange(1, 1, 1, 15).getValues()
for (var iFile = 1; iFile<aFiles.length; iFile ++){
var org = aFiles[iFile][0];
var name = aFiles[iFile][1];
var id= aFiles[iFile][2];
var ssI = SpreadsheetApp.openById(id);
var sData = ssI.getSheetByName("Data");
var lRow = sData.getLastRow();
if (lRow >= 2){
var aNew =[];
aNew = sData.getRange(2, 1, sData.getLastRow(), 15).getValues();
aData.concat(aData,aNew);
}
}
var lDRow = sDa.getLastRow();
sDa.getRange(2, 1, lDRow , 15).clear()
var rng = sDa.getRange(1, 1, aData.length, 15);
rng.setValues(aData);
Logger.log(aData.length)
}
The data in the tables is strucutred in the following way:
Spreadsheet A:
Org Name Hours Comment
A Joe 15 Weekend
A Pete 20 Sunday
A Maik 15 test
Spreadsheet B
Org Name Hours Comment
B Will 15 Monday
B Anna 18 holiday
B Dave 10 test
...
And so one.
Has anybody an idea how I can combine those data and create a "joint database"?
Issue:
aData.concat(aData,aNew);
Array.concat doesn't concat in-place. It returns the concatenated array.
Solution:
Use the returned array:
aData = aData.concat(aData,aNew);
Alternatively use flatMap,
const out = aFiles.flatMap(([org, name, id])=>
SpreadsheetApp.openById(id)
.getSheetByName('Data')
.getDataRange()//TODO Modify range according to last row
.getValues())

Storing an Array in Google App Script and Printing an Array to Google Sheets Column

I'm working on a Google Sheets and I'm trying to store an column of integers in an array, then clear a column on the sheet and then print the array of integers to a column on the sheet. Please see below for code...
function myFunction1() {
//Declaring the Active Sheet
var mySheet = SpreadsheetApp.getActiveSheet();
//Declaring the range that will make up the Array
var myRange = mySheet.getRange("E10:E328");
//Declaring Array
var myArray = [[myRange.getValues()]];
//Clearing a range on the Google Sheet
mySheet.getRange('A10:A328').clearContent();
//Printing Array to Google Sheet
mySheet.getRange(15, 5).setValues([myArray]);
}
The above code runs without any errors but does not print my array to the sheet. I've been working on this for a while and have used the following articles to try to fix it...
https://productforums.google.com/forum/#!topic/docs/t99laH0rFc0
Incorrect Range Height - Google Script
Writing 1D array into a sheet column in Apps Script
https://developers.google.com/apps-script/reference/spreadsheet/range#setvaluesvalues
Common errors that i have had when writing the code up to this point is, "Incorrect Range Height" and "Cannot convert Array to Object[][]".
How would i fix this so that my Array prints to the column on the sheet?
Thanks for your time! Any help on this would be great!!
You're making it a bit more complex than you have to.
function myFunction1() {
//Declaring the Active Sheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var mySheet = ss.getActiveSheet();
//Declaring the range that will make up the Array
var myArray = mySheet.getRange("E10:E328").getValues();//already in an array
//Clearing a range on the Google Sheet
mySheet.getRange('A10:A328').clearContent();
//Printing Array to Google Sheet
mySheet.getRange(15, 5).setValues(myArray); //already in an array don't need brackets
}
// Write data in cell G1, H1, I1
function arrayPlay() {
var newArray = [];
// Variable that saves the data from G1->I1.
var cellIn1 = ("G1");
var cellIn2 = ("H1");
var cellIn3 = ("I1");
var sheet = SpreadsheetApp.getActiveSheet();
// Defines where the data is recieved. (G1, H1, I1)
var cellOut1 = sheet.getRange(cellIn1);
var cellOut2 = sheet.getRange(cellIn2);
var cellOut3 = sheet.getRange(cellIn3);
// Recieve the data from those cells
var data1 = cellOut1.getValue();
var data2 = cellOut2.getValue();
var data3 = cellOut3.getValue();
// Puts the data in the Array. (newArray)
newArray.push(data1, data2, data3)
// Presents the data in Cell 1-3 (A1, A2, A3)) Downwards
sheet.appendRow([newArray[0]]);
sheet.appendRow([newArray[1]]);
sheet.appendRow([newArray[2]]);
// Presents the data in Cell 1-3 (A1, B1, C1) Sideways
sheet.appendRow([newArray[0], newArray[1], newArray[2]]);
Logger.log(newArray);
}
It is hard to tell exactly what you are trying to do. But if you are trying to replace column A with column E, just do this:
function myFunction1() {
var mySheet = SpreadsheetApp.getActiveSheet();
var myRange = mySheet.getRange("E10:E328").getValues();
mySheet.getRange('A10:A328').setValues(myRange);
}

How to split a javascript array using Google Script

I'm working on a project that outputs a huge array, and I need to clean it up to send in an email. It seems the simplest approach is the split() function, but I can't seem to make it work.
function splitArray() {
var ss = SpreadsheetApp.getActiveSheet();
var row = ss.getLastRow();
var range = ss.getRange(row, 1, 1, ss.getMaxColumns());
var data = range.getValues();
data.split("\n");
Logger.log(data);}
You need to set the return value of data.split("\n"); to something.
You are splitting the value successfully but not storing that value anywhwere
Try:
data = data.split("\n");
or
Logger.log(data.split("\n"));

Categories