Copy and Past multiple rows. Ljava.lang.Object response - google-apps-script

I'm writing a little script to automatically copy/past some data from one sheet to another sheet.
I've come up with the following script :
function test() {
var sheet = SpreadsheetApp.openById('1sLVRDzzOopFQrXLNtAYKfyBfJthCkjvK8xe_PtOmso0').getSheetByName('Sheet1');
var numRows = sheet.getLastRow()-1;
for(var i = 0; i < numRows; i++) {
// Dispatching Data
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2")
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1")
var data1 = sheet.getRange('Sheet1!A2:G2').getValues();
sheet.appendRow([data1]);
ss.deleteRow(2)
}
}
It's working perfectly fine but return me the following response :
Ljava.lang.Object response... for each row.
What should I do ? thanks !

If you want to use your script then the simple fix is to change:
sheet.appendRow([data1]);
to:
sheet.appendRow(data1[0]);
because you only want the 1 row.
However I'm not sure what the point of your for loop is? This might be a little cleaner:
function test() {
var ss = SpreadsheetApp.openById('ID')
var sheet1 = ss.getSheetByName("Sheet1")
var sheet2 = ss.getSheetByName("Sheet2")
var data1 = sheet1.getRange('Sheet1!A2:G2').getValues();
sheet2.appendRow(data1[0]);
sheet1.deleteRow(2)
}

Related

How to make this script run faster?

Hello so I am trying to get values from the 'book' sheet then copy it to 'Completed' sheet. It takes the values form book stores it in the data array and copy them to the 'Completed' sheet. Its working fine but very slow which jeopardizes my work in time-wise. How can I make this run faster ?
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var clear_sheet = spreadsheet.getSheetByName('Completed_Orders'); // clear the destination sheet first
clear_sheet.getRange('A2:X').clear();
var sheet = spreadsheet.getSheetByName('book'); //source sheet
var Datarange = sheet.getRange('Q3:Q'); //range to check
var Datavalue = (Datarange.getValues());
var dest = spreadsheet.getSheetByName('Completed_Orders'); //destination sheet
var data = [];
for (i=0; i<Datavalue.length;i++) {
if ( Datavalue[i] == "Completed") {
data.push.apply(data,sheet.getRange(i+3,1,1,24).getValues());
}
}
dest.getRange(2,1,data.length,data[0].length).setValues(data);
var column = dest.getRange('A3:A');
var values = column.getValues(); // get all data in one call
var ct = 0;
while ( values[ct][0] != "" ) { // to find the last row correctly, getLastRow is not working perfectly
ct++;
}
var endRow = ct+2;
}
Try this:
Don't use this syntax var values=sheet.getRange('A3:A').getValues() because it get's the data all the way down to getMaxRows(). Instead use var values=sheet.getRange(3,1,sheet.getLastRow()-2,1).getValues().
Also Datavalue[i] is a whole row
function myfunction() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var clear_sheet = spreadsheet.getSheetByName('Completed_Orders');
clear_sheet.getRange(2,1,clear_sheet.getLastRow()-1,24).clear();
var sheet = spreadsheet.getSheetByName('book'); //source sheet
var Datarange = sheet.getRange(3,17,sheet.getLastRow()-2,1); //range to check
var Datavalue = Datarange.getValues();
var dest = spreadsheet.getSheetByName('Completed_Orders'); //destination sheet
var data = [];
for (var i=0;i<Datavalue.length;i++) {
if (Datavalue[i]["************You need another index here**************"] == "Completed") { //need another index Datavalue is 2d
data.push(sheet.getRange(i+3,1,1,24).getValues());
}
}
dest.getRange(2,1,data.length,data[0].length).setValues(data);
}
I think this version will be a lot faster.
function myfunction() {
var ss=SpreadsheetApp.getActiveSpreadsheet();
var ssh=ss.getSheetByName('book');
var dsh=ss.getSheetByName('Completed_Orders');
dsh.getRange(2,1,dsh.getLastRow()-1,24).clear();
var dv=ssh.getRange(3,1,ssh.getLastRow()-2,24).getValues();//this version just gets this data one time so it should a lot faster.
var data=[];
for (var i=0;i<dv.length;i++) {
if (dv[i][16]=="Completed") {
data.push(dv[i]);
}
}
dsh.getRange(2,1,data.length,data[0].length).setValues(data);
}

Google Apps Script to list all Google Classroom courses and put them in a Google Spreadsheet

I am trying to create a Google Apps Script that will list all the Google Classroom courses that are active and archived, along with the ID, NAME, SECTION, and COURSESTATE. Everything works except that I have no idea how to fix the .getRange so that it will put all the information in the Google Spreadsheet. The error I get is "Incorrect range height, was 4 but should be 10". If I put the .getRange as simply "A1:D1", it will overwrite what is there for each Class until the script finishes, so I know the rest of the script works, but I can't figure out how to put the range so that all the Classes can be listed. What I have up to now is this:
function listCourses() {
var response = Classroom.Courses.list();
var courses = response.courses;
if (courses && courses.length > 0) {
for (i = 0; i < courses.length; i++) {
var course = courses[i];
var ids = course.id;
var title = course.name;
var sec = course.section;
var state = course.courseState;
var arr1 = [];
arr1.push(ids,title,sec,state);
var arr2 = [];
while(arr1.length) arr2.push(arr1.splice(0,1));
var s = SpreadsheetApp.getActiveSpreadsheet();
var sh = s.getSheetByName('LISTS');
for (var x=0; x<arr2.length; x++){
var newRow = sh.getLastRow() + 1;
// Here in the .getRange is where it gives me the error. A new row should be added for each Class until all the Classes (with the information mentioned above) are listed.
sh.getRange(1, 1, newRow, arr2[0].length).setValues(arr2);
}
}}}
Try something like this:
I don't use Classroom API much and I only have one class in it but this works for it.
function listCourses() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getSheetByName('LISTS');
var response = Classroom.Courses.list();
var courses = response.courses;
var arr=[];//You could put column headers in here
for (i = 0; i < courses.length; i++) {
var course = courses[i];
var ids = course.id;
var title = course.name;
var sec = course.section;
var state = course.courseState;
arr.push([title,sec,state]); //you could also go sh.appendRow([title,sec,state]); here if you wish and avoid the use of the two dimensional array all together as suggested in the other answer.
}
sh.getRange(1, 1, arr.length, arr[0].length).setValues(arr);
}
Jason. You could bypass the range issue by using append row. This will however mean manipulating the data so that each class's details is on one row. I prefer this approach because it is let prone to errors. Also it automatically finds the next empty row in the sheet, so you don't need to get the last row.
function appendRow() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Sheet1');
// Try is added to catch failures on automated scripts
try {
sheet.appendRow(['cell1','cell2','cell3'])
} catch (e){
Logger.log(e)
// Could send an email here to alert script failure
}
// In a loop
var data = [['row 1 cell 1','row 1 cell 2'],['row 2 cell 1','row 2 cell 2 ']]
data.forEach(function(item){
sheet.appendRow(item)
})
}

google sheets script conditionally move row to another spreadsheet

I am new to this and I am having some trouble trying to figure this out. I have a spreadsheet that collects data from a google form. I am trying to find a way to move that data based on a column answer to a different google sheet. (Not a sheet in the same document but a different document all together). It seems like there is some information about moving to a different tab in the same document, but not a different document.
I will first say that I tried just an IMPORTRANGE function, but that only mirrors the data, and does not let you update or change cells.
Here is what I have been able to piece together so far, but I may be way off.
I have a trigger that would run every hour.
function myFunction() {
var ss = SpreadsheetApp.openById('1U0I9SkbGkHgm-vRkwf2Ppc_yxlqrVlg2t8yKRy3sYuI');
var sheetOrg = ss.getSheetByName("Form Responses 1");
var value1ToWatch = "ANDERSON";
var value2ToWatch = "BARNES";
var sheetNameToMoveTheRowTo = "Sheet1"; //sheet has same name for each target openByID(" *url key* ")
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ts1 =SpreadsheetApp.openById("1PxV1PQrMdu_2aSru4dpan8cUgHYdlYPUp5anyzjMAms");
sheet1in = ts1.getSheetByName("Sheet1");
var ts2 = SpreadsheetApp.openById("1BYyQZNiXc2QqsyqWs7uazjl5B6mfFYM1xj3u8gWyYOQ");
sheet1in = ts2.getSheetByName("Sheet1");
arr = [],
values = sheetOrg.getDataRange().getValues(),
i = values.length;
while (--i) {
if (value1ToWatch.indexOf(values[i][1]) > -1) {
arr.unshift(values[i])
sheetOrg.deleteRow(i + 1)
sheet1in.getRange(sheet1in.getLastRow()+1, 1, arr.length,
arr[0].length).setValues(arr);
};
if (value2ToWatch.indexOf(values[i][1]) > -1) {
arr.unshift(values[i])
sheetOrg.deleteRow(i + 1)
sheet2in.getRange(sheet2in.getLastRow()+1, 1, arr.length,
arr[0].length).setValues(arr);
};
}
}
The sheet google forms dumps the information into is "Form Responses 1".
Column B is the cells I want to get the values from. (There are a total of 9 different values that it can be like "ANDERSON", "BARNES", "SMITH", etc).
For sheetNameToMoveTheRowTo is "Sheet1" - that may be confusing and I may need to change that, but for example
ts1 =SpreadsheetApp.openById("1PxV1PQrMdu_2aSru4dpan8cUgHYdlYPUp5anyzjMAms") the sheet name that I want the information moved to is "Sheet1".
ts2 = SpreadsheetApp.openById("1BYyQZNiXc2QqsyqWs7uazjl5B6mfFYM1xj3u8gWyYOQ") the sheet name is also "Sheet1" but in a different document.
I think if I were able to get the "ANDERSON" one to work, then I can just add additional variables for each possible response, and just copy and paste additional "IF" statements, just changing the valueToWatch and targetSheet values. <= if that is not correct please let me know
I have tried to both debug, and run the script above but nothing happens. There are no errors reported on the debug, but it is not moving any information over.
Any idea what I am doing wrong?
// UPDATE I got this to work. I have updated the code listed with what worked for me.
I think that copyTo() method will not work like you mentioned, it operates on same SpreadSheet. I'm sending you example with looping on source sheet data and then setting the target sheet values with it.
function myFunction() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var allrange = ss.getActiveRange();
var range = sheet.getRange("A1:A10");
var values = range.getValues();
var allvals = [];
for(var i = 0; i < values.length; i++) {
allvals.push( values[i] ) ;
}
var dataLength = allvals.length;
// alert data
var ui = SpreadsheetApp.getUi();
// ui.alert( JSON.stringify(allvals) )
// copy to new Google SpreadSheet
var newSheet = SpreadsheetApp.openById('1F79XkNPWm2cCWlB2JP3K4tAYRESKUgtHK4Pn2vbJEiI').getSheets()[0];
var tmp = "A1:A" + dataLength ;
var newRange = newSheet.getRange( tmp );
newRange.setValues( allvals );
}
Here's a simple example of moving data from one spreadsheet to another.
function movingDataToSS(){
var ss=SpreadsheetApp.getActive();
var dss=SpreadsheetApp.openById('ssId');
var sh=ss.getActiveSheet();
var rg=sh.getDataRange();
var vA=rg.getValues();
var dsh=dss.getSheetByName('Sheet1');
var drg=dsh.getRange(1,1,rg.getHeight(),rg.getWidth()).setValues(vA);
}
If you interested in placing some conditions on your output by only getting output from odd rows and even columns.
function movingDataOddRowsAndEvenCols(){
var ss=SpreadsheetApp.getActive();
var dss=SpreadsheetApp.openById('ssId');
var sh=ss.getActiveSheet();
var rg=sh.getDataRange();
var vA=rg.getValues();
var h=rg.getHeight();
var w=rg.getWidth();
var dsh=dss.getSheetByName('Sheet1');
for(var i=0;i<h;i++){
var out=[];
if(i%2==0){
for(var j=0;j<w;j++){
if(j%2==1){
out.push(vA[i][j]);
}
}
dsh.appendRow(out);
}
}
}

for each in ss.getSheets() get a range of data

I'm struggling on a child task within a function I'm working on.
For each sheet in sheets, I would like to get the data in range A16:D, combine into one big array and then out put the combined data into a new sheet. But each time I try to select each data range it comes as undefined?
How can I get the data from each sheet in sheets and then add into one big array?
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ranges = [];
function combineData() {
var activeSheetName = ss.getActiveSheet().getName();
var sheets = ss.getSheets();
sheets.forEach(function(e) {
var sheetName = e.getName();
if (sheetName != activeSheetName && sheetName != 'Report Configuration' && sheetName != 'Sheet1')
var wee_data = e.getRange('A16:D').getValues(); // TROUBLE HERE, WEE_DATA IS UNDEFINED
for(var j = 0; j<wee_data.length; j++) {
store.push(wee_data[j]);
}
ranges.push(wee_data);
});
if (ranges.length) {
Logger.log('range length is: ' + ranges.length);
adjustSheetLength(); // ensure there are enough rows in the destination sheet.
// figure out how to output data array "ranges" into a sheet "combined".
}
}
function adjustSheetLength(){
var comb = ss.getSheetByName('combined');
var lastRow = 4;
var maxRows = comb.getLastRow();
comb.deleteRows(lastRow, maxRows-lastRow);
var datapullSize = ranges.length;
comb.insertRows(4, datapullSize-2);// insert exactly the number of rows you need.
}
I think your issue is in the .forEach callback function. When I debugged those functions I got a not allowed in callback exception.
Change the foreach to a for in I think that'll fix your issue.
for( var i in sheets ) {
Logger.log(sheets[i]);
...
}

google script - json into google sheet

I'm new to scripting and I would appreciate your help. I do apologize for what might be a simple question.
What I have is an api that gives json:
[{"id":"xyz","name":"xy"},
{"id":"zyx","name":"yx"}]
The above continues lets say for another 100 ids.
What I want is to put that into the cells in google spreadsheet.
What I have currently is:
var ss = SpreadsheetApp.getActive();
var sh = ss.getActiveSheet();
var rr = sh.getRange(3,2,100,5);
var id = "www.xyz.com/api";
var jsonData = UrlFetchApp.fetch(id);
var jsonString = jsonData.getContentText();
var idsearch = JSON.parse(jsonString);
for (var i = 1; i < idsearch.count; i++)
{
var cellid = rr.getCell(i,1);
eventid.setValue(idsearch.results[i].id);
var cellname = rr.getCell(i,2);
eventname.setValue(idsearch.results[i].name);
}
When I run the script, nothing happens. It doesnt return anything.
Did I make a mistake in the script? Is there an easier way to put all the json result into google sheet? Is there an example where I can look at to learn about what I'm trying to do?
Thank you very much.
I hope this simple code might help you.
function myFunction() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ss.getSheets();
var sheet = ss.getActiveSheet();
var dataSet = [
{"id":"xyz","name":"xy"},
{"id":"zyx","name":"yx"}
];
var rows = [],
data;
for (i = 0; i < dataSet.length; i++) {
data = dataSet[i];
rows.push([data.id, data.name]);
}
dataRange = sheet.getRange(1, 1, rows.length, 2);
dataRange.setValues(rows);
}
You might also want to inspect the example here (it's based on ScriptDb but will work with any JSON array).
https://developers.google.com/apps-script/scriptdb#copy_a_database_to_a_new_sheet_in_a_spreadsheet