I have read all the previous posts and I have a similiar subjetc that I can't solve. I have to copy/paste a Google Sheets (two sheets, 'GENERAL', 'VALEUR') document.
I have won to write a code to copy/paste : 1 document (source) ==to==> 1 document (destination)
function expCalc(){
copypaste_GENERAL();
copypaste_VALEUR();
}
function copypaste_GENERAL() {
var source_G = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/1xTBgfI-yy30GHm-LpsUWWoLRACNk5rdc81DPKGyS9fw/edit#gid=0');
var sourceSheet_G = source_G.getSheetByName('GENERAL');
var sourceRange_G = sourceSheet_G.getDataRange();
var sourceValues_G = sourceRange_G.getValues();
var tempSheet_G = source_G.getSheetByName('TEMP_GENERAL');
var tempRange_G = tempSheet_G.getRange('A1:DU11');
var destination_G = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/1kFKaNOc8JbRM63tb24QB3_fJms5vnQbZj2lOYsoh0CA/edit#gid=1580219321');
var destSheet_G = destination_G.getSheetByName('GENERAL');
sourceRange_G.copyTo(tempRange_G); // paste all formats?, broken references
tempRange_G.offset(0, 0, sourceValues_G.length, sourceValues_G[0].length)
.setValues(sourceValues_G); // paste all values (over broken refs)
copydSheet = tempSheet_G.copyTo(destination_G); // now copy temp sheet to another ss
copydSheet.getDataRange().copyTo(destSheet_G.getDataRange());
destination_G.deleteSheet(copydSheet); //delete copydSheet
}
function copypaste_VALEUR() {
var source_V = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/1xTBgfI-yy30GHm-LpsUWWoLRACNk5rdc81DPKGyS9fw/edit#gid=0');
var sourceSheet_V = source_V.getSheetByName('VALEUR');
var sourceRange_V = sourceSheet_V.getDataRange();
var sourceValues_V = sourceRange_V.getValues();
var tempSheet_V = source_V.getSheetByName('TEMP_VALEUR');
var tempRange_V = tempSheet_V.getRange('A1:I255');
var destination_V = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/1kFKaNOc8JbRM63tb24QB3_fJms5vnQbZj2lOYsoh0CA/edit#gid=1580219321');
var destSheet_V = destination_V.getSheetByName('VALEUR');
sourceRange_V.copyTo(tempRange_V); // paste all formats?, broken references
tempRange_V.offset(0, 0, sourceValues_V.length, sourceValues_V[0].length)
.setValues(sourceValues_V); // paste all values (over broken refs)
copydSheet = tempSheet_V.copyTo(destination_V); // now copy temp sheet to another ss
copydSheet.getDataRange().copyTo(destSheet_V.getDataRange());
destination_V.deleteSheet(copydSheet); //delete copydSheet
}
but I can't write a code to copy/paste : 1 document (source) ==to==> MANY (more than 1) documents (destination) according to a list of URLs (here, example only on 2 URLs)
Here is my test code (using only t'GENERAL' sheet for this present test)
function copypaste_GENERAL() {
var source = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/1xTBgfI-yy30GHm-LpsUWWoLRACNk5rdc81DPKGyS9fw/edit#gid=0');
var sourceSheet = source.getSheetByName('GENERAL');
var sourceRange = sourceSheet.getDataRange();
var sourceValues = sourceRange.getValues();
var tempSheet = source.getSheetByName('TEMP_GENERAL');
var tempRange = tempSheet.getRange('A1:DU11');
var destSpreadUrl = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/1kFKaNOc8JbRM63tb24QB3_fJms5vnQbZj2lOYsoh0CA/edit#gid=1580219321');
var destSheetUrl = destSpreadUrl.getSheetByName('URLTST');
var destSheet_G = destSpreadUrl.getSheetByName('GENERAL');
var urlessai = destSheetUrl.getRange("D2:D3").getValues();
for (var row = 1; row = 3; row++) {
if (urlessai[row] != '') {
sourceRange.copyTo(tempRange); // paste all formats?, broken references
tempRange.offset(0, 0, sourceValues.length, sourceValues[0].length)
.setValues(sourceValues); // paste all values (over broken refs)
copydSheet = tempSheet.copyTo(destSpreadUrl); // now copy temp sheet to another ss
copydSheet.getDataRange().copyTo(destSheet_G.getDataRange());
destSpreadUrl.deleteSheet(copydSheet); //delete copydSheet
};
};
};
Please, can you help me to find a solution to write this copy/paste loop on a list of URLs (for x users) ?
Thanks in advance !
Philippe
This is probably not exactly what you want but I think it's close and I'm willing to tweak it.
function copySrcDes() {
const ss = SpreadsheetApp.getActive();
const locs = [{srcid:"1xTBgfI-yy30GHm-LpsUWWoLRACNk5rdc81DPKGyS9fw",desid:"1kFKaNOc8JbRM63tb24QB3_fJms5vnQbZj2lOYsoh0CA",shts:["GENERAL"]},{srcid:"1xTBgfI-yy30GHm-LpsUWWoLRACNk5rdc81DPKGyS9fw",desid:"1kFKaNOc8JbRM63tb24QB3_fJms5vnQbZj2lOYsoh0CA",shts:["VALEUR"]}];
locs.forEach(obj => {
let sss = SpreadsheetApp.openById(obj.srcid);
let dss = SpreadsheetApp.openById(obj.desid);
obj.shts.forEach(n => {
let ssh = sss.getSheetByName(n);
let dsh = dss.getSheetByName(n);
let vs = ssh.getDataRange().getValues();
dsh.getRange(1,1,vs.length,vs[0].length).setValues(vs);
});
});
}
Related
I have found so many scripts to copy values only from one spreadhseet to another. However, all of them is to copy the whole spreasheet.
I am very new with google script and cannot find a way to copy values only from specific tabs to another spreasheet adding these new tabs to it.
function temp() {
var sss = SpreadsheetApp.openById('XYZ'); // sss = source spreadsheet
//var ss = sss.getSheets()[4]; // ss = source sheet
var ss = sss.getSheets(); // ss = source sheet
var id=4; //default number
for(var i in ss)
{
var sheet = ss[i];
if(sheet.getName()== "ABC")
{ id=i;
break;
}
}
console.log(id);
ss=sss.getSheets()[id];
//Get full range of data
var SRange = ss.getDataRange();
//get A1 notation identifying the range
var A1Range = SRange.getA1Notation();
//get the data values in range
var SData = SRange.getValues();
SpreadsheetApp.flush();
var tss = SpreadsheetApp.getActiveSpreadsheet(); // tss = target spreadsheet
var ts = tss.getSheetByName('ABC'); // ts = target sheet
//set the target range to the values of the source data
ts.getRange(A1Range).setValues(SData);
}
Thanks a lot in advance.
Issue:
You can to copy the values from a specific set of sheets to a new spreadsheet.
I assume that you don't want to copy the sheet itself, but only the values from the source sheet.
Modifications:
Use filter to get an array of your desired sheets (based on sheet name).
If the target spreadsheet doesn't have a sheet with that name, create it with Spreadsheet.insertSheet.
Code sample:
function temp() {
var sheetNames = ["ABC", "DEF"]; // Change accordingly
var sss = SpreadsheetApp.openById('XYZ');
var sheetsToCopy = sss.getSheets().filter(s => sheetNames.includes(s.getSheetName()));
sheetsToCopy.forEach(ss => {
var sourceSheetName = ss.getSheetName();
var SRange = ss.getDataRange();
var A1Range = SRange.getA1Notation();
var SData = SRange.getValues();
var tss = SpreadsheetApp.getActiveSpreadsheet();
var ts = tss.getSheetByName(sourceSheetName);
if (!ts) ts = tss.insertSheet(sourceSheetName);
ts.getRange(A1Range).setValues(SData);
});
}
Copy these sheets to another spreadsheet
function copythese() {
const ss = SpreadsheetApp.getActive();
const these = ['Sheet0','Sheet1'];//Put your sheetnames here
const another = SpreadsheetApp.openById("another id");//put the other spreadsheet id here
ss.getSheets().filter(sh => ~these.indexOf(sh.getName())).forEach(sh => {
sh.copyTo(another);
});
}
Append These Values to another spreadsheet
function appendthesevalues() {
const ss = SpreadsheetApp.getActive();
const these = ['Sheet0','Sheet1'];
const another = SpreadsheetApp.openById("another id");
ss.getSheets().filter(sh => ~these.indexOf(sh.getName())).forEach(sh => {
let vs = sh.getDataRange().getValues();
let nsh = another.getSheetByName(sh.getName());
if(!nsh) {
nsh = another.insertSheet(sh.getName());
SpreadsheetApp.flush();
}
if(nsh) {
nsh.getRange(nsh.getLastRow() + 1, 1 ,vs.length, vs[0].length).setValues(vs);
}
});
}
I have this code. I want to loop through the array and create a new doc for each entry. If I manually set the loop length to the number of rows it works fine. I want to set it to loop for the length of the array. However the .length property always returns null. What am I missing. I have also tried for each loops with no luck.
function createDocument()
{
//var headers = Sheets.Spreadsheets.Values.get('fileID', 'A1:Z1');
var studentHistory = Sheets.Spreadsheets.Values.get('fileID', 'A2:Z200');
var templateId = 'fileID';
var documentId;
var dstFolder = DriveApp.getFolderById('folderID');
var length = studentHistory.length;
Logger.log(studentHistory);
Logger.log(length);
//Loop through rows in sheet
for (var i = 0; i < length; i++){
//Get values from sheet row
var date = studentHistory.values[i][0];
var studentName = studentHistory.values[i][1];
var dob = studentHistory.values[i][2];
var pcDoctor = studentHistory.values[i][3];
var address = studentHistory.values[i][4];
var fgName = studentHistory.values[i][5];
var mgName = studentHistory.values[i][6];
var phoneMom = studentHistory.values[i][7];
var phoneDad = studentHistory.values[i][8];
var empMom = studentHistory.values[i][9];
var empDad = studentHistory.values[i][10];
var livesWith = studentHistory.values[i][11];
var childrenInHome = studentHistory.values[i][12];
var childrenNotInHome = studentHistory.values[i][13];
var othersInHome = studentHistory.values[i][14];
var illnesses = studentHistory.values[i][15];
var illnessDetails = studentHistory.values[i][16];
var hospitalizations = studentHistory.values[i][17];
var hospDetails = studentHistory.values[i][18];
var trauma = studentHistory.values[i][19];
var traumaDetails = studentHistory.values[i][20];
var injuries = studentHistory.values[i][21];
var injuryDetails = studentHistory.values[i][22];
var medications = studentHistory.values[i][23];
var additionalComments = studentHistory.values[i][24];
var otherSchools = studentHistory.values[i][25];
//Make a copy of the template file
documentId = DriveApp.getFileById(templateId).makeCopy(dstFolder).getId();
//Change name of newly created document
DriveApp.getFileById(documentId).setName('SocialHistory_' + studentName + '_' + date);
var body = DocumentApp.openById(documentId).getBody();
//Insert values
body.replaceText('<<date>>', date);
body.replaceText('<<studentName>>', studentName);
body.replaceText('<<dob>>', dob);
body.replaceText('<<pcDoctor>>', pcDoctor);
body.replaceText('<<address>>', address);
body.replaceText('<<fgName>>', fgName);
body.replaceText('<<mgName>>', mgName);
body.replaceText('<<phoneMom>>', phoneMom);
body.replaceText('<<phoneDad>>', phoneDad);
body.replaceText('<<empMom>>', empMom);
body.replaceText('<<empDad>>', empDad);
body.replaceText('<<livesWithe>>', livesWith);
body.replaceText('<<childrenInHome>>', childrenInHome);
body.replaceText('<<childrenNotInHome>>', childrenNotInHome);
body.replaceText('<<othersInHome>>', othersInHome);
body.replaceText('<<illnesses>>', illnesses);
body.replaceText('<<illnessDetails>>', illnessDetails);
body.replaceText('<<hospitalizations>>', hospitalizations);
body.replaceText('<<hospDetails>>', hospDetails);
body.replaceText('<<trauma>>', trauma);
body.replaceText('<<traumaDetails>>', traumaDetails);
body.replaceText('<<injuries>>', injuries);
body.replaceText('<<injuryDetails>>', injuryDetails);
body.replaceText('<<medications>>', medications);
body.replaceText('<<additionalComments>>', additionalComments);
body.replaceText('<<otherSchools>>', otherSchools);
}
}
studentHistory.values is the array.
Therefore, try this instead to get the length:
var length = studentHistory.values.length;
Solution
I see you are using Advanced Google Services to call the Sheets API. This Apps Script class allows you to call the Google APIs directly from your script handling automatically the authorization process.
However it doesn't work as the built in Classes that are available for example inside the SpreadsheetApp wrapper.
Your request will return an HTTP-like response following these specifications:
{
"range": string,
"majorDimension": enum (Dimension),
"values": [
array
]
}
You will need to parse these responses in order to achieve the desired result.
Proposed modification
function createDocument()
{
//var headers = Sheets.Spreadsheets.Values.get('fileID', 'A1:Z1');
var studentHistory = Sheets.Spreadsheets.Values.get('fileID', 'A2:Z200');
var templateId = 'fileID';
var documentId;
var dstFolder = DriveApp.getFolderById('folderID');
var length = studentHistory.values.length;
...
Reference
Google Sheets API
Advanced Google Services
I am trying to use a file name to get data from a Spreadsheet, and copy the data into a different target file. I have the following code, and it is failing at line 7. When I manually put in an ID in line 7 the code works. Could someone help? Thank you very much.
function openFile() {
var fileList = DriveApp.getFilesByName('file name')
while (fileList.hasNext()) {
Logger.log(fileList.next().getId())
}
var fileID = Logger.getLog();
var ss = SpreadsheetApp.openById(fileID);//fails here
var source = ss.getSheetByName('sheet name');
var rangeSource = source.getDataRange();
var data = rangeSource.getValues();
var rowsInData = data.length;
var colsInData = data[0].length;
var sss = SpreadsheetApp.openById('1Hia3_zGk1qyPlVuPTQR5iOjExFaMEe3EQOMXBc2C6eI');
var logSheet = sss.getSheetByName("diamondbackprogress");
var rowsInLogSheet = logSheet.getMaxRows();
var colsInLogSheet = logSheet.getMaxColumns();
if (rowsInLogSheet < rowsInData) {
logSheet.insertRowsAfter(rowsInLogSheet, rowsInData - rowsInLogSheet);
} else if (rowsInLogSheet > rowsInData) {
logSheet.deleteRows(rowsInData, rowsInLogSheet - rowsInData);
}
if (colsInLogSheet < colsInData) {
logSheet.insertColumnsAfter(colsInLogSheet, colsInData - colsInLogSheet);
} else if (colsInLogSheet > colsInData) {
logSheet.deleteColumns(colsInData, colsInLogSheet - colsInData);
}
logSheet.getRange(1, 1, rowsInData, colsInData).setValues(data);
}
Logger.getLog() won't give you the id of the file, it will give a list of messages in the current log. See here for more details.
Replace this part:
function openFile() {
var fileList = DriveApp.getFilesByName('file name')
while (fileList.hasNext()) {
Logger.log(fileList.next().getId())
}
var fileID = Logger.getLog();
with this:
function openFile() {
var fileList = DriveApp.getFilesByName('file name')
while (fileList.hasNext()) {
var fID = fileList.next().getId();
}
var fileID = fID;
I have a project I been working on to read data from one sheet and iterate through the designated columns grab that data and place it on a template that will be uploaded to Google ads. See the code below (A SIMPLE LOOP IS NEEDED SEE MY CODE FOR COMMENTS!). Please note that i'm new to this and it may look like an eye sore. I been stuck on this for a while now trying literally everything I found with no success. if you need additional attachments or clarification please let me know.
//============================================================================*
// This program is an inventory based program that will create AdGroups based *
// On your current inventory Spreadsheet on your G-Drive *
// ===========================================================================*
function main() {
var feedCSVname = "FILE_NAME.csv"
var feedSheetName = "INVENTORY SHEET"
var TemplateURL = "SHEET_URL_HERE"
var Template_sheetName = "TEMPLATE_SHEET_NAME"
var push_sheetName = "Upload"
var done = "Done"
// ==== Parse CSV file and dump all contents to inventory sheet =========
var feedFile = DriveApp.getFilesByName(feedCSVname).next();
var feedData = Utilities.parseCsv(feedFile.getBlob().getDataAsString());
var Template = SpreadsheetApp.openByUrl(TemplateURL);
var feedSheet = Template.getSheetByName(feedSheetName);
feedSheet.clear().getRange(1, 1, feedData.length, feedData[0].length).setValues(feedData);
// Create a new columns "Status" so we can loop through
feedSheet.getRange('BI1').setValue('Status');
//==================== Feed Column Locations ============================
var CidColumn = 2;
var sellingPriceColumn = 10;
var yearColumn = 13;
var makeColumn = 14;
var modelColumn = 15;
var trimColumn = 16;
var dealernameColumn = 39;
var countofmakemodelyearColumn = 47;
var lowest_priceColumn = 52;
var mm_lowest_priceColumn = 53;
var m_lowest_priceColumn = 54;
var URL1Column = 58;
var URL2Column = 59;
var URL3Column = 60;
var status = 61;
var feedRows = 2 // Since row 1 has headers
var lastrow = feedSheet.getLastRow();
//======================= Feed Row Data ================================
var sellingPrice = feedSheet.getRange(feedRows, sellingPriceColumn).getValue();
var year = feedSheet.getRange(feedRows, yearColumn).getValue();
var make = feedSheet.getRange(feedRows, makeColumn).getValue();
var model = feedSheet.getRange(feedRows, modelColumn).getValue();
var dealername = feedSheet.getRange(feedRows, dealernameColumn).getValue();
var URL1 = feedSheet.getRange(feedRows, URL1Column).getValue();
var URL2 = feedSheet.getRange(feedRows, URL2Column).getValue();
var URL3 = feedSheet.getRange(feedRows, URL3Column).getValue();
//==================== Write Data To Template ==========================
// I need to loop this process
var templateSheet = Template.getSheetByName(Template_sheetName);
templateSheet.getRange('B2').setValue("Campaign Name");
templateSheet.getRange('B3').setValue(make);
templateSheet.getRange('B4').setValue(model);
templateSheet.getRange('B5').setValue(year);
templateSheet.getRange('D2').setValue(URL1);
templateSheet.getRange('D3').setValue(URL2);
templateSheet.getRange('D4').setValue(URL3);
feedSheet.getRange(feedRows, status).setValue(done);
// when this column and row = "Done" then go to next row
var readStatusColumn = feedSheet.getRange(feedRows, status).getValue();
if (readStatusColumn == done) {
//Then go to next row loop process
}
//================ Copy all data to push sheet =========================
//Copy contents of the Template sheet and paste to the Upload sheet
var copyRange = templateSheet.getRange('A8:J113');
var pushSheet = Template.getSheetByName(push_sheetName);
var paste2pushSheet = pushSheet.getRange(pushSheet.getLastRow() + 1, 1);
copyRange.copyTo(paste2pushSheet, {
contentsOnly: true
});
//End Loop
}
I'm new to GAS. I'm trying to accomplish four tasks in a single spreadsheet with three separate sheets to relate to.
I want to copy data from the 'rawData sheet', set it in an array, rearrange the array, and set the values in the 'destination sheet'. And keep it active for new submissions (i.e. getLastRow/appendRow).
In 'destination sheet' I want to color code based on status.
Create a button in 'destination sheet' to mark row(case) complete and move from 'destination' to the 'complete sheet'.
And add onEdit triggers for each.
Your input is greatly appreciated.
Thanks.
function colorCode() {
var range = outerArray;
Logger.log(range);
var row = dBoard.getRange(dBoard.getLastRow(),1,1,dBoard.getLastColumn());
var submitter = range[3];
var status = range[11];
Logger.log(submitter);
Logger.log(status);
//var column = range.getColumn();
//var row = range.getRow();
if (status === "Approved"){
var rowToColor = row.offset(0,0,1,13);
rowToColor.setBackground("#6bb2ff");
}
else if (status === "Requester"){
var rowToColor = row.offset(0,0,1,13);
rowToColor.setBackground("#ffe16b");
}
else if (range === 12 && range > 1 && status === "Denied"){
var rowToColor = row.offset(0,0,1,13);
rowToColor.setBackground("#f9441b");
}
}
var ss = SpreadsheetApp.getActiveSpreadsheet();
var source1 = ss.getSheetByName("Copy of rawData");
var dBoard = ss.getSheetByName("dBoard2");
//function copyData() {
//var rawD = source1.getRange(1,1,source1.getLastRow(),source1.getLastColumn()).getValues();
//Logger.log(rawD);
function setData() {
var rawD = source1.getRange(source1.getLastRow(),1,1,source1.getLastColumn()).getValues();
//Logger.log(limits);
var columnA = rawD[0][0];
var columnB = rawD[0][18];
var columnC = rawD[0][13];
var columnD = rawD[0][2];
var columnE = rawD[0][3]
var columnF = rawD[0][4];
var columnG = rawD[0][5];
var columnH = rawD[0][6];
var columnI = rawD[0][7];
var columnJ = rawD[0][8];
var columnK = rawD[0][9];
var columnL = rawD[0][11];
var columnM = rawD[0][12];
var outerArray = [columnA,
columnB,
columnC,
columnD,
columnE,
columnF,
columnG,
columnH,
columnI,
columnJ,
columnK,
columnL,
columnM];
Logger.log(columnA);
Logger.log(columnB);
Logger.log(outerArray);
dBoard.getRange(2,1,outerArray.length,outerArray.length);
dBoard.appendRow(outerArray);
}