How to extract few cells from a Google Sheet and copy to another sheet using a single statement - arrays

using JavaScript to access google sheets via google API.
I am copying the entire content of a "google spreadsheet" "Parent sheet" into a two dimension array vaParent
var ssParent = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Parent");
var vaParent = ssParent.getRange(2, 1, ssParent.getLastRow(), ssParent.getLastColumn() ).getValues();
I am extracting 6 array elements
var vaNewParent01 = vaParent[i].slice(3, 9);
Now, I would like to copy vaNewParent01 to a new google "spreadsheet" "company sheet"
ssCompany.getRange( 2, 1 ).setValues( vaNewParent01 );
above code does not work??
I've found that vaNewParent01 is a single dimension array with 6 elements
however, ssCompany.getRange( 2, 1 ).setValues( vaNewParent01
only works if vaNewParent01 is an array of array
question:
a/ how to extract few cells from a sheet and copy to another using a single statement.
thanks in advance for any help
cheers

From your showing script, if your script is like the following script,
var ssParent = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Parent");
var vaParent = ssParent.getRange(2, 1, ssParent.getLastRow(), ssParent.getLastColumn()).getValues();
for (var i = 0; i < vaParent.length; i++) {
var vaNewParent01 = vaParent[i].slice(3, 9);
ssCompany.getRange(2, 1).setValues(vaNewParent01);
}
vaNewParent01 is 1 dimensional array. In order to use setValues(values), values is required to be 2 dimensional array. And about ssCompany.getRange( 2, 1 ).setValues( vaNewParent01 );, in this case, please include the numbers of rows and columns of the values you want to put. If my understanding of your situation is correct, I think that the reason for your issue is due to this.
About how to extract few cells from a sheet and copy to another using a single statement., in this case, how about the following sample script?
Sample script 1:
This script is modified from your showing script by guessing your tested script.
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ssParent = ss.getSheetByName("Parent");
var ssCompany = ss.getSheetByName("sample"); // Please set the destination sheet name.
var vaParent = ssParent.getRange(2, 1, ssParent.getLastRow(), ssParent.getLastColumn()).getValues();
var values = [];
for (var i = 0; i < vaParent.length; i++) {
var vaNewParent01 = vaParent[i].slice(3, 9);
values.push(vaNewParent01);
}
ssCompany.getRange(2, 1, values.length, values[0].length).setValues(values);
Sample script 2:
As other sample script, how about the following script? In this sample script, copyTo of Class Range is used. From your showing script, I thought that you wanted to copy the values from D2:I of the source sheet to A2 of the destination sheet.
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ssParent = ss.getSheetByName("Parent");
var ssCompany = ss.getSheetByName("sample"); // Please set the destination sheet name.
var src = ssParent.getRange("D2:I" + ssParent.getLastRow());
src.copyTo(ssCompany.getRange(2, 1), { contentsOnly: true });
References:
setValues(values)
copyTo(destination, options)

arr is single dimension array
let vs = arr.map(e => [e]); //for a column;
let vs = [arr]; //for a row
Sheet.getRange(1,1,vs.length, vs[0].length).setValues(vs);

Related

Apps Script: Move SELECTED rows from one sheet to the last available rows of another sheet

The code below is from here and was originally written by user #Cooper. All it does is that it copies the values of the columns specified in the array colA = [1,3,2,4] from SHEET 1 and add them to SHEET 2. I want to re-write the 2 last lines of the code, so that the values coming from SHEET 1 are added to the last available rows in SHEET 2. By "2 last lines", I mean these last lines of the code:
drng = des.getRange(1,1,drngA.length,drngA[0].length);//destination array controls size of destination range.drng.setValues(drngA);
Any idea how to get this done?
Thank you so much in advance for your help!
function Copy_data()
{
var src = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("SHEET 1");
var des = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("SHEET 2");
var srng = src.getDataRange();
var srngA = srng.getValues();
var drngA = [];
var colA = [1,3,2,4];//indirect data column selection
for (var i = 0; i < srngA.length;i++ )
{
var k = 0;
drngA[i]=[];
for(var j=0;j<srngA[i].length;j++)
{
drngA[i][k++] = srngA[i][colA[j]-1];
}
drng = des.getRange(1,1,drngA.length,drngA[0].length);//destination array controls size of destination range.
drng.setValues(drngA);
}
}
You can get the last row of the destination Sheet and after, add it to your getRange() function. The method proposed by #soMario will not work because it makes requests inside the loop while you update the Sheet, and this causes it to get different values every time you call des.getLastRow().
The simplest solution is to take the getLastRow() request outside of the loop and then include it in getRange. Note that one is added to it so that it does not overwrite the last row with the setValue() request.
Code.gs
function Copy_data() {
...
var lastRow = des.getLastRow() + 1
for (var i = 0; i < srngA.length;i++ ){
...
drng = des.getRange(lastRow,1,drngA.length,drngA[0].length)
...
}
Documentation
getRange(row, column, numRows, numColumns)
getLastRow()

Google Apps Script Copy/Paste Filtered DataSet

I've been trying to write a script that simply takes a filtered data, copies it, and then pastes it into another sheet. Nothing I seem to do works. With the code below, which I found online, it should work, but I keep getting an error that states The number of rows in the range must be at least 1. However, I have data in the range A7:R500 and I'm only filtering out blanks and 'W'. Am I correct in this thinking?
function copyPaste(){
var sheet = SpreadsheetApp.getActiveSheet();
var values = sheet.getRange('A7:R500').getValues();
var hiddenValues = ['', 'W'];
values = values.filter(function(v){
return hiddenValues.indexOf(v[4]) == 'W';
});
sheet.getRange(1,21, values.length, 18).setValues(values);
}
Solution:
Since you are already using a filter Array, you can compare hiddenValues.indexOf(v[4]) to -1 to filter out blanks and "W".
Also, since your goal is to paste the results in a different sheet, you need to define both the source and the destination sheet. Create a sheet and plug its name into the new sheet name tag in the code below.
Sample Code:
function copyPaste() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet1 = ss.getActiveSheet();
var sheet2 = ss.getSheetByName('<new sheet name>');
var values = sheet1.getRange('A7:R500').getValues();
var hiddenValues = ['', 'W'];
values = values.filter(function(v){
return hiddenValues.indexOf(v[4]) == -1;
});
sheet2.getRange(1,21, values.length, 18).setValues(values);
}
Reference:
indexOf()

Google Apps Script: how to create an array of values for a given value by reading from a two column list?

I have a set of data in a Google spreadsheet in two columns. One column is a list of article titles and the other is the ID of a hotel that is in that article. Call it list1.
Example data
I would like returned a new list with article titles in one column, and an array of the hotel IDs in that article in the other column. Call it list2.
Example data
There are thousands of lines that this needs to be done for, and so my hope was to use Google Apps Script to help perform this task. My original thinking was to
Create column 1 of list2 which has the unique article titles (no script here, just the G-sheets =unique() formula.
Iterate through the titles in list2, looking for a match in first column of the list1
If there is a match:
retrieve its corresponding value in column 2
push it to an empty array in column two of list2
move onto next row in list1
if no longer a match, loop back to step 2.
I've written the following code. I am currently getting a type error (TypeError: Cannot read property '0' of undefined (line 13, file "Code")), however, I wanted to ask whether this is even a valid approach to the problem?
function getHotelIds() {
var outputSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('list2');
var lastRow = outputSheet.getLastRow();
var data = outputSheet.getRange(2,1,lastRow,2).getValues();
var workingSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('list1');
var lastActiveRow = workingSheet.getLastRow();
var itemIDS = [];
for (var i=1; i<=data.length; i++) {
var currentArticle = data[i][0];
var lookupArticle = workingSheet[i][0];
if (currentArticle === lookupArticle) {
var tempValue = [workingSheet[i][1]];
itemIDS.push(tempValue);
}
}
}
Use a simple google sheets formula:
You can use a very simple formula to achieve your goal instead of using long and complicated scripts.
Use =unique(list1!A2:A) in cell A2 of list2 sheet to get the unique hotels.
and then use this formula to all the unique hotels by dragging it down in column B.
=JOIN(",",filter(list1!B:B,list1!A:A=A2))
You got the idea right, but the logic needed some tweaking. The "undefined" error is caused by the workingSheet[i][0]. WorkingSheet is a Sheet object, not an array of data. Also, is not necessary to get the data from list2 (output), it is rather the opposite. You have to get the data from the list1 (source) sheet instead, and iterate over it.
I added a new variable, oldHotel, which will be used to compare each line with the current hotel. If it's different, it means we have reached a different Hotel and the data should be written in list2.
function getHotelIds() {
var outputSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('list2');
var outLastRow = outputSheet.getLastRow();
var workingSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('list1');
var lastActiveRow = workingSheet.getLastRow();
var sourceValues = workingSheet.getRange("A2:B" + lastActiveRow).getValues();
var itemIDS = [];
var oldHotel = sourceValues[0][0]; //first hotel of the list
for (var i = 0; i < sourceValues.length; i++) {
if (sourceValues[i][0] == oldHotel) {
itemIDS.push(sourceValues[i][1]);
/*When we reach the end of the list, the oldHotel variable will never be different. So the next if condition is needed. Otherwise it wouldn't write down the last Hotel.
*/
if (i == sourceValues.length - 1) {
outputSheet.getRange(outLastRow + 1, 1, 1, 2).setValues([
[sourceValues[i][0], itemIDS.toString()]
]);
}
} else {
outputSheet.getRange(outLastRow + 1, 1, 1, 2).setValues([
[sourceValues[i - 1][0], itemIDS.toString()]
]);
oldHotel = sourceValues[i][0]; //new Hotel will be compared
outLastRow = outputSheet.getLastRow(); //lastrow has updated
itemIDS = []; //clears the array to include the next codes
}
}
}
I also converted the itemIDS array to a String each time, so it's written down in a single cell without issues.
Make sure each column of the Sheet is set to "Plain text" from Format > Number > Plain Text
References
getRange
setValues
toString()

setFormulas and rangeList

I'm trying to setFormulas over a range of non-contiguous cells. I need a formula (they're all different) set every 30 cells in a single column (c).
It works to setFormula for each cell, but creating 56 variables seems unnecessary. I can get the formulas but not set them as intended. I also tried using getRangeList but I'm not sure that does what I think it does. Any advice?
function test() {
var spreadsheetU09U10 = SpreadsheetApp.openById('some url');
var sheetU09 = spreadsheetU09U10.getSheetByName('TEST');
var sheetU10 = spreadsheetU09U10.getSheetByName('U10');
var sheetDATA = spreadsheetU09U10.getSheetByName('Sheet4');
//U09 SHEET
//var rangeListU09 = sheetU09.getRangeList(['C4','C34','C64','C94','C124','C154','C184','C204','C234','C264','C294','C324','C354','C384','C404','C434','C464','C494',
//'C524','C554','C584','C604','C634','C664','C694','C724','C754','C784']);
//Logger.log(rangeListU09);
var startRow = 4;
var startColumn = 3;
var numRows = sheetU09.getLastRow();
var numColumns = 1;
var range = sheetU09.getRange(startRow, startColumn, numRows, numColumns);
var getFormulasU09 = sheetDATA.getRange('C30:C57').getFormulas();
//Logger.log(getFormulasU09);
Logger.log(getFormulasU09.length);
for (var i = 0; i < getFormulasU09.length; i++) {
var setFormulasU09 = range.setFormulas(getFormulasU09);
Logger.log(setFormulasU09);
startRow = startRow + 29;
}
It isn't clear exactly where the formulas you are using are originating from, but the RangeList class can help reduce the read time, even if you use it just to call getRanges. If the formula is the same in R1C1 format, then you can very effectively use RangeList#setFormulaR1C1.
Assuming you have formulas in one region that must be written verbatim in a disjoint set of cells:
const wb = SpreadsheetApp.getActive();
// Assuming only text formulas, not actual "entered" formulas
const formulas = wb.getSheetByName("formulas").getDataRange()
.getValues()
.map(function (row) { return row[0]; });
const sheet = wb.getSheetByName("some name");
const destinations = [
// Depending on the relationship between destinations, one could programmatically generate these
];
// Efficiently acquire references to multiple disjoint Ranges
const rl = sheet.getRangeList(destinations);
// Assume the i-th formula goes in the i-th range
rl.getRanges().forEach(function (rg, i) {
rg.setFormula(formulas[i]);
});
// The RangeList makes uniformly formatting these disjoint ranges extremely simple
rl.setFontWeight('bold');
...
Reference
- RangeList
You want to put formulas to the individual cells.
You want to put 28 formulas to cells of ['C4','C34','C64','C94','C124','C154','C184','C204','C234','C264','C294','C324','C354','C384','C404','C434','C464','C494', 'C524','C554','C584','C604','C634','C664','C694','C724','C754','C784'] in the sheet of TEST.
If my understanding is correct, how about using values.batchUpdate of Sheets API? The flow of this script is as follows.
Set range list as 1 dimensional array.
Retrieve formulas.
Create request body for sheets.spreadsheets.values.batchUpdate.
In order to use this script, please enable Sheets API at Advanced Google Services and API console. You can see about how to enable Sheets API at here.
Sample script:
function test() {
var spreadsheetId = "### spreadsheetId ###"; // Please set this.
var sheetName = "TEST";
var spreadsheetU09U10 = SpreadsheetApp.openById(spreadsheetId);
var sheetU09 = spreadsheetU09U10.getSheetByName(sheetName);
// var sheetU10 = spreadsheetU09U10.getSheetByName('U10'); // This is not used in this script.
var sheetDATA = spreadsheetU09U10.getSheetByName('Sheet4');
var rangeListU09 = ['C4','C34','C64','C94','C124','C154','C184','C204','C234','C264','C294','C324','C354','C384','C404','C434','C464','C494', 'C524','C554','C584','C604','C634','C664','C694','C724','C754','C784'];
var getFormulasU09 = sheetDATA.getRange('C30:C57').getFormulas();
rangeListU09 = rangeListU09.map(function(e) {return sheetName + "!" + e});
var resource = {
data: rangeListU09.map(function(e, i) {return {range: e, values: [[getFormulasU09[i][0]]]}}),
valueInputOption: "USER_ENTERED",
};
Sheets.Spreadsheets.Values.batchUpdate(resource, spreadsheetId);
}
Note:
From your question, I'm not sure about the detail formulas. If the a1Notation of each formulas is required to be modified, can you provide a sample spreadsheet including the formulas?
Reference:
sheets.spreadsheets.values.batchUpdate
If I misunderstand your question, please tell me. I would like to modify it.
I'm assuming that you want to copy the whole column starting from the cell locations in the array. That wasn't really clear to me.
function test109() {
var ss=SpreadsheetApp.getActive();
var shU09=ss.getSheetByName('35');//formulas get copied into here starting at row 4
var shDATA=ss.getSheetByName('36');//formulas stored in here C30:C57
var fA=shDATA.getRange('C30:C57').getFormulas();
var dA=['C4','C34','C64','C94','C124','C154','C184','C204','C234','C264','C294','C324','C354','C384','C404','C434','C464','C494','C524','C554','C584','C604','C634','C664','C694','C724','C754','C784'];
for(var i=0;i<dA.length;i++){
var rgs=Utilities.formatString('%s:%s',dA[i],shU09.getRange(dA[i]).offset(fA.length-1,0).getA1Notation());//this uses range.offset to calculate the correct range in A1Notation.
shU09.getRange(rgs).setFormulas(fA);
}
}
As it turns out I just noticed that there are 28 locations and 28 formulas. Perhaps that was intentional and you want to copy a different formula in each location then this version would do that.
function test109() {
var ss=SpreadsheetApp.getActive();
var shU09=ss.getSheetByName('35');//formulas get copied into here starting at row 4
var shDATA=ss.getSheetByName('36');//formulas stored in here C30:C57
var fA=shDATA.getRange('C30:C57').getFormulas();
var dA=['C4','C34','C64','C94','C124','C154','C184','C204','C234','C264','C294','C324','C354','C384','C404','C434','C464','C494','C524','C554','C584','C604','C634','C664','C694','C724','C754','C784'];
for(var i=0;i<dA.length;i++){
shU09.getRange(dA[i]).setFormula(fA[i][0]);
}
}
Range Offset

Get data from a lot of different sheets with a script in Google Spreadsheet

I have a spreadsheet containing 50 sheets, named "1", "2", "3". The very first sheet is a summary, gathering specific information from the different sheets. The simple way to fill it in is by using ='1'!B5 and so on. What I want to do is enter that formula into a script and have it pull the specified data from all the different sheets on new rows. So that info from sheet 1 is at row 1, info from sheet 2 is on row 2.
The reason I don't want to do it manually is that I have 14 cells that I need to pull and insert into 4 different overviews from 50 sheets and 2 spreadsheets where I need to do this. Adding up to 5600 functions that I would need to change manually.
The reason I named the sheets in this simple manner is that I know it enables me to write this kind of function. A variable that increases its value by 1 for every loop and outputs the function on a new row with every loop, for instance
var sheetName = 0;
output.setValue('='' + sheetName + ''!B5');
I know I should have a variable for the specified output cell that also increase its value by 1 for every loop. But I have no idea how to get this sorted out, my scripting skills only allow me to modify others script to make them suit my own purposes but not write anything by myself and I have been unable to figure this one out more then the theory behind it. I know this isn't the place to ask for ready made code so I don't demand or even expect a solution, I just felt I had to try and ask for aid.
Here is a dummy which shows what I'm trying to do.
https://docs.google.com/spreadsheet/ccc?key=0ArjDeqGD779cdEh2Ynh5ODBFQVFkVE9lX0p4aWpXelE&usp=sharing#gid=0
You are a lucky man Mattis! I was doing this thing myself earlier this week so I have added a full working script to your dummy sheet. I'll add a copy here for completeness. Any questions please let me know :)
function populateOverview() {
//set basics
var ss = SpreadsheetApp.getActiveSpreadsheet();
var viewSheet = ss.getSheetByName('Overview');
var dataLength = 4; //this is how many cells from each sheet
//create array of sheet names and remove 'overview'
var sheetNames = getSheetNames();
var overviewIndex = sheetNames.indexOf('Overview');
sheetNames.splice(overviewIndex, 1);
//set initial data and target columns
var dataColumn = 2;
var dataRow = 2;
var targetColumn = 3;
var j = 0;
//outer loop iterates through sheets
for (var i = 0; i < sheetNames.length; i++){
//inner loop works across the columns in each sheet, and across the column on the overview
for(var k = 0; k < dataLength; k++){
viewSheet.getRange(j+3, targetColumn+k).setValue(ss.getSheetByName(sheetNames[i]).getRange(dataRow, dataColumn).getValue());
dataColumn = dataColumn + 2;
}
//increments row counter for next sheet input
j = j+1;
//resets for next sheet
dataColumn = 2;
targetColumn = 3;
}
}
/*return sheetnames as array*/
function getSheetNames(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheetArray = ss.getSheets();
var sheetNameArray = [];
for(var i = 0; i<sheetArray.length; i++){
sheetNameArray.push(sheetArray[i].getSheetName());
}
return sheetNameArray;
}

Resources