importJSON in Google Sheet reduce API connections? - google-apps-script

I have made an other question here:
First question
It seems I'm calling to much the API.
My script calls 23 times the API in one go.
This is how my script looks like :
var ss = SpreadsheetApp.getActiveSheet();
//Creates a menu called Crypto.
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Crypto')
.addItem('Update Prices','updatePrices')
.addItem('Update Sheet','updateSheet')
.addToUi();
}
//Copy cells.
function copyCell() {
ss.getRange("D2:D13").copyTo(ss.getRange("E2"), {contentsOnly:true});
ss.getRange("B2:B13").copyTo(ss.getRange("G2"), {contentsOnly:true});
ss.getRange("M1").copyTo(ss.getRange("M2"), {contentsOnly:true});
ss.getRange("M5").copyTo(ss.getRange("M6"), {contentsOnly:true});
}
/**
* Imports JSON data to your spreadsheet Ex: IMPORTJSON("https://api.coinmarketcap.com/v2/ticker/1/?convert=EUR","data/quotes/EUR/price")
* #param url URL of your JSON data as string
* #param xpath simplified xpath as string
* #customfunction
*/
function IMPORTJSON(url,xpath){
try{
// /rates/EUR
var res = UrlFetchApp.fetch(url);
var content = res.getContentText();
var json = JSON.parse(content);
var patharray = xpath.split("/");
//Logger.log(patharray);
for(var i=0;i<patharray.length;i++){
json = json[patharray[i]];
}
//Logger.log(typeof(json));
if(typeof(json) === "undefined"){
return "Node Not Available";
} else if(typeof(json) === "object"){
var tempArr = [];
for(var obj in json){
tempArr.push([obj,json[obj]]);
}
return tempArr;
} else if(typeof(json) !== "object") {
return json;
}
}
catch(err){
return "Error getting data";
}
}
//Importing CMC Data into sheet
function importCMC() {
var btc_eur = IMPORTJSON("https://api.coinmarketcap.com/v2/ticker/1/?convert=EUR","data/quotes/EUR/price");
var btc_btc = IMPORTJSON("https://api.coinmarketcap.com/v2/ticker/1/?convert=BTC","data/quotes/BTC/price");
ss.getRange("B2").setValue([btc_eur]);
ss.getRange("H2").setValue([btc_btc]);
var bhc_eur = IMPORTJSON("https://api.coinmarketcap.com/v2/ticker/1831/?convert=EUR","data/quotes/EUR/price");
var bhc_btc = IMPORTJSON("https://api.coinmarketcap.com/v2/ticker/1831/?convert=BTC","data/quotes/BTC/price");
ss.getRange("B3").setValue([bhc_eur]);
ss.getRange("H3").setValue([bhc_btc]);
var ltc_eur = IMPORTJSON("https://api.coinmarketcap.com/v2/ticker/2/?convert=EUR","data/quotes/EUR/price");
var ltc_btc = IMPORTJSON("https://api.coinmarketcap.com/v2/ticker/2/?convert=BTC","data/quotes/BTC/price");
ss.getRange("B4").setValue([ltc_eur]);
ss.getRange("H4").setValue([ltc_btc]);
var ada_eur = IMPORTJSON("https://api.coinmarketcap.com/v2/ticker/2010/?convert=EUR","data/quotes/EUR/price");
var ada_btc = IMPORTJSON("https://api.coinmarketcap.com/v2/ticker/2010/?convert=BTC","data/quotes/BTC/price");
ss.getRange("B5").setValue([ada_eur]);
ss.getRange("H5").setValue([ada_btc]);
var trx_eur = IMPORTJSON("https://api.coinmarketcap.com/v2/ticker/1958/?convert=EUR","data/quotes/EUR/price");
var trx_btc = IMPORTJSON("https://api.coinmarketcap.com/v2/ticker/1958/?convert=BTC","data/quotes/BTC/price");
ss.getRange("B6").setValue([trx_eur]);
ss.getRange("H6").setValue([trx_btc]);
var neo_eur = IMPORTJSON("https://api.coinmarketcap.com/v2/ticker/1376/?convert=EUR","data/quotes/EUR/price");
var neo_btc = IMPORTJSON("https://api.coinmarketcap.com/v2/ticker/1376/?convert=BTC","data/quotes/BTC/price");
ss.getRange("B7").setValue([neo_eur]);
ss.getRange("H7").setValue([neo_btc]);
var ont_eur = IMPORTJSON("https://api.coinmarketcap.com/v2/ticker/2566/?convert=EUR","data/quotes/EUR/price");
var ont_btc = IMPORTJSON("https://api.coinmarketcap.com/v2/ticker/2566/?convert=BTC","data/quotes/BTC/price");
ss.getRange("B8").setValue([ont_eur]);
ss.getRange("H8").setValue([ont_btc]);
var gas_eur = IMPORTJSON("https://api.coinmarketcap.com/v2/ticker/1785/?convert=EUR","data/quotes/EUR/price");
var gas_btc = IMPORTJSON("https://api.coinmarketcap.com/v2/ticker/1785/?convert=BTC","data/quotes/BTC/price");
ss.getRange("B9").setValue([gas_eur]);
ss.getRange("H9").setValue([gas_btc]);
var enj_eur = IMPORTJSON("https://api.coinmarketcap.com/v2/ticker/2130/?convert=EUR","data/quotes/EUR/price");
var enj_btc = IMPORTJSON("https://api.coinmarketcap.com/v2/ticker/2130/?convert=BTC","data/quotes/BTC/price");
ss.getRange("B10").setValue([enj_eur]);
ss.getRange("H10").setValue([enj_btc]);
var tky_eur = IMPORTJSON("https://api.coinmarketcap.com/v2/ticker/2507/?convert=EUR","data/quotes/EUR/price");
var tky_btc = IMPORTJSON("https://api.coinmarketcap.com/v2/ticker/2507/?convert=BTC","data/quotes/BTC/price");
ss.getRange("B11").setValue([tky_eur]);
ss.getRange("H11").setValue([tky_btc]);
var uuu_eur = IMPORTJSON("https://api.coinmarketcap.com/v2/ticker/2645/?convert=EUR","data/quotes/EUR/price");
var uuu_btc = IMPORTJSON("https://api.coinmarketcap.com/v2/ticker/2645/?convert=BTC","data/quotes/BTC/price");
ss.getRange("B12").setValue([uuu_eur]);
ss.getRange("H12").setValue([uuu_btc]);
var cmc_usd = IMPORTJSON("https://api.coinmarketcap.com/v2/global/","data/quotes/USD/total_market_cap");
ss.getRange("M1").setValue([cmc_usd]);
}
//Getting euro prices from Coincapmarket and place them in specific cells.
function updatePrices() {
copyCell();
importCMC();
//Get current date
var now = new Date();
ss.getRange('F1').setValue(now)
}
//Getting euro prices from Coincapmarket and place them in specific cells.
function updateSheet() {
copyCell();
importCMC();
//Get date.
var now = new Date();
ss.getRange('F1').setValue(now)
ss.getRange("F1").copyTo((ss.getRange(ss.getRange("A18:A111").getValues().filter(String).length + 18, 1)), {contentsOnly:true});
ss.getRange("D15").copyTo((ss.getRange(ss.getRange("B18:B111").getValues().filter(String).length + 18, 2)), {contentsOnly:true});
//Copy the formula's from row 19 to last filled cell in A and B.
var row = 19;
CopyFormulasDown.copyFormulasDown(ss, row);
}
The problem with V2 api of CMC is that the BTC price has to be checked with an other URL. I'm not a hero in array's. Sorry.
I'm thinking of pulling four times the ticker API and then find the right info
1. https://api.coinmarketcap.com/v2/ticker/?convert=EUR
2. https://api.coinmarketcap.com/v2/ticker/?convert=EUR&start=101
3. https://api.coinmarketcap.com/v2/ticker/?convert=EUR&start=201
4. https://api.coinmarketcap.com/v2/ticker/?convert=EUR&start=301
Because the api limits to 100 tickers I have to create 4. I'm using V2 of the IP and I'm using the ID to get the right currency. That is the number behind the ticker. I have to use 4 downloads because The highest rank of currency is 316.
What is the best way to optimize this script with out calling to much api's?

I have reduced my script. It now has 4 api calls. Sometimes still to much for coinmarketcap.
var ss = SpreadsheetApp.getActiveSheet();
//Creates a menu called Crypto.
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Crypto')
.addItem('Update Prices','updatePrices')
.addItem('Update Sheet','updateSheet')
.addToUi();
}
//Copy cells.
function copyCell() {
ss.getRange("D2:D13").copyTo(ss.getRange("E2"), {contentsOnly:true});
ss.getRange("B2:B13").copyTo(ss.getRange("G2"), {contentsOnly:true});
ss.getRange("M1").copyTo(ss.getRange("M2"), {contentsOnly:true});
ss.getRange("M5").copyTo(ss.getRange("M6"), {contentsOnly:true});
}
//Importing CMC Data into sheet
function importCMC() {
var response = UrlFetchApp.fetch("https://api.coinmarketcap.com/v2/ticker/?convert=EUR");
var content = response.getContentText();
var json = JSON.parse(content);
var btc_eur = json["data"]["1"]["quotes"]["EUR"]["price"];
ss.getRange("B2").setValue([btc_eur]);
var bch_eur = json["data"]["1831"]["quotes"]["EUR"]["price"];
ss.getRange("B3").setValue([bch_eur]);
var ltc_eur = json["data"]["2"]["quotes"]["EUR"]["price"];
ss.getRange("B4").setValue([ltc_eur]);
var ada_eur = json["data"]["2010"]["quotes"]["EUR"]["price"];
ss.getRange("B5").setValue([ada_eur]);
var trx_eur = json["data"]["1958"]["quotes"]["EUR"]["price"];
ss.getRange("B6").setValue([trx_eur]);
var neo_eur = json["data"]["1376"]["quotes"]["EUR"]["price"];
ss.getRange("B7").setValue([neo_eur]);
var ont_eur = json["data"]["2566"]["quotes"]["EUR"]["price"];
ss.getRange("B8").setValue([ont_eur]);
var gas_eur = json["data"]["1785"]["quotes"]["EUR"]["price"];
ss.getRange("B9").setValue([gas_eur]);
Utilities.sleep(5000)
var response = UrlFetchApp.fetch("https://api.coinmarketcap.com/v2/ticker/?convert=EUR&start=101");
var content = response.getContentText();
var json = JSON.parse(content);
var enj_eur = json["data"]["2130"]["quotes"]["EUR"]["price"];
ss.getRange("B10").setValue([enj_eur]);
var tky_eur = json["data"]["2507"]["quotes"]["EUR"]["price"];
ss.getRange("B11").setValue([tky_eur]);
Utilities.sleep(5000)
var response = UrlFetchApp.fetch("https://api.coinmarketcap.com/v2/ticker/2645/?convert=EUR");
var content = response.getContentText();
var json = JSON.parse(content);
var uuu_eur = json["data"]["quotes"]["EUR"]["price"];
ss.getRange("B12").setValue([uuu_eur]);
Utilities.sleep(5000)
var response = UrlFetchApp.fetch("https://api.coinmarketcap.com/v2/global/");
var content = response.getContentText();
var json = JSON.parse(content);
var cmc_usd = json["data"]["quotes"]["USD"]["total_market_cap"];
ss.getRange("M1").setValue([cmc_usd]);
}
//Getting euro prices from Coincapmarket and place them in specific cells.
function updatePrices() {
copyCell();
importCMC();
//Get current date
var now = new Date();
ss.getRange('F1').setValue(now)
}
//Getting euro prices from Coincapmarket and place them in specific cells.
function updateSheet() {
copyCell();
importCMC();
//Get date.
var now = new Date();
ss.getRange('F1').setValue(now)
ss.getRange("F1").copyTo((ss.getRange(ss.getRange("A18:A111").getValues().filter(String).length + 18, 1)), {contentsOnly:true});
ss.getRange("D15").copyTo((ss.getRange(ss.getRange("B18:B111").getValues().filter(String).length + 18, 2)), {contentsOnly:true});
//Copy the formula's from row 19 to last filled cell in A and B.
var row = 19;
CopyFormulasDown.copyFormulasDown(ss, row);
}

Related

when i run my script to fetch data from other 2 sheets it is arranged the shown in picture of master sheet

master sheet
this is my code
the names are displayed under names numbers to be displayed under numbers but it is displayed under names ..I have 2 sheets named as{name,number} and a master sheet contains id,name number.
when i run the script it ftches data but not accordingly
function addMenu()
{
var menu = SpreadsheetApp.getUi().createMenu('Merge');
menu.addItem('Run Script', 'MergeSheets');
menu.addToUi();
}
function onOpen()
{
addMenu();
}
//combine data from multiple sheets
function MergeSheets() {
var app = SpreadsheetApp;
var ss = app.getActiveSpreadsheet();
var data = null;
var RetrieveSheet = null;
var PasteSheet = ss.getSheetByName("Master");
var sheets = ['Name','Number'];
PasteSheet.getRange(2,1,PasteSheet.getLastRow(),PasteSheet.getLastColumn()).clear();
for (var i =0; i<sheets.length; i++){
RetrieveSheet = ss.getSheetByName(sheets[i]);
if (RetrieveSheet.getName() != 'Master'){
data = RetrieveSheet.getRange(2,1,RetrieveSheet.getLastRow(),RetrieveSheet.getLastColumn());
data.copyTo(PasteSheet.getRange(parseInt(PasteSheet.getLastRow())+1,1));
}
}
}
//update data changes to each sheets
function updateBasedSheet()
{
var master = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Master');
var valueMaster = master.getRange(2, 1, master.getLastRow(), master.getLastColumn()).getValues();
var Name = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Name');
var Number = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Number');
var dataName = valueMaster.filter( function(item){
return item[2] === 'Name';
}
);
var Number = valueMaster.filter( function(item){
return item[2] === 'Number';
});
Name.getRange(1, 3, dataName.length, dataName[0].length).setValues(dataName);
Number.getRange(1, 3, dataNumber.length, dataNumber[0].length).setValues(dataNumber);
}
If you simply want to join 2 sheets, and they have same length and id correspondesce, you can use
var data1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Name').slice(1);
var data2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Number').slice(1);
var mergedData = data1.map( (index, row) => row.concat(data2[index]) );
SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Master')
.getRange(2, 1, mergedData.length, mergedData[0].length)
.setValues(mergedData);

RefreshImport function not working in Google Sheets

I tried to fill it with my sheet data, but that
var dataRange = sheet.getDataRange();
get an error. What should I do?
function RefreshImports() {
var lock = LockService.getScriptLock();
if (!lock.tryLock(5000)) return; // Wait up to 5s for previous refresh to end.
var id = "1r7TgCWXfjmcjufT0yz9qcFDlr482SdHDHlZYblXyAt0"; // [YOUR SPREADSHEET ID]
var ss = SpreadsheetApp.openById(id);
var sheet = ss.getSheetByName("crypto"); // sheet name
var dataRange = sheet.getDataRange();
var formulas = dataRange.getFormulas();
var content = "";
var now = new Date();
var time = now.getTime();
var re = /.*[^a-z0-9]import(?:xml|data|feed|html|range)\(.*/gi;
var re2 = /((\?|&)(update=[0-9]*))/gi;
var re3 = /(",)/gi;
for (var row=0; row<formulas.length; row++) {
for (var col=0; col<formulas[0].length; col++) {
content = formulas[row][col];
if (content != "") {
var match = content.search(re);
if (match !== -1 ) {
// import function is used in this cell
var updatedContent = content.toString().replace(re2,"$2update=" + time);
if (updatedContent == content) {
// No querystring exists yet in url
updatedContent = content.toString().replace(re3,"?update=" + time + "$1");
}
// Update url in formula with querystring param
sheet.getRange(row+1, col+1).setFormula(updatedContent);
}
}
}
}
// Done refresh; release the lock.
lock.releaseLock();
// Show last updated time on sheet somewhere
sheet.getRange(7,2).setValue("Rates were last updated at " + now.toLocaleTimeString())
}
I set up the trigger.
Not sure what you trying to do and you explanation leaves a lot to be desired.
So this is a simple way to put your formulas into a sheet named "Destination".
function RefreshImports() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName("crypto");
const rg = sh.getDataRange();
const formulas = rg.getFormulas();
sh.getRange(1,1,formulas.length,formulas[0].length).setFormulas(formulas);
}

Required permissions: https://www.googleapis.com/auth/spreadsheets in a custom function

I have read through the official documentation that states, you are not allowed to use services that require authorization such as SpreadsheetApp.openById within a custom function.
I am using a script to call a spreadsheet in its functions and it's doing that fluently. My custom function is not using the service SpreadsheetApp.openById, but still tells me that I do not have the permission. I just want to know whether it is possible to run the custom function or not, even though I am not calling a spreadsheet in the function itself?
Updated:
My custom function build's a reference id for a particular quotation.
I've also tried using https://www.googleapis.com/auth/spreadsheets in oauthScopes in the json file, didn't work.
This is the function calling openById:
var ss1 = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var dukeid = "1WGbEo1Xr99HwHY_4ZaeTRIgCOuNcjVfqCzZx4dcQX4I"
var duke = SpreadsheetApp.openById(dukeid);
var totalstockd = duke.getSheetByName("Total Stock").getRange(2,3,2500,7).getValues();
var avmid = "1a6bm2O_iljHZUoF2BhYeyxUT13tB06-JJCYeYCZZ10Q"
var avm = SpreadsheetApp.openById(avmid);
var totalstocka = avm.getSheetByName("Total Stock").getRange(2,3,1000,7).getValues();
function when(e){
var activeCell = e.range;
var val = activeCell.getValue();
var r = activeCell.getRow();
var c = activeCell.getColumn();
var ssName = activeCell.getSheet().getName();
if (ssName=="General Information" && (r==3 || r==6) && c==3){
var rescell = ss1.getRange(r,6);
var unitcell = ss1.getRange(r,7);
rescell.clearContent();
if(val[0]=="A"){
var result = sumalt(val,totalstocka,unitcell);
rescell.setValue(result);
}
else {
var result = sumalt(val,totalstockd,unitcell);
rescell.setValue(result);
}
}
else{
console.log("No Edit");
}
}
And this is my custom function:
function QREF(Company,ID){
var td=new Date().valueOf();
var year = new Date().getFullYear();
var hd=new Date(year, 0, 0).valueOf();
var year2 = year - 2000
var sec=1000;
var min=60*sec;
var hour=60*min;
var day=24*hour;
var diff=td-hd;
var julian=Math.floor(diff/day);
Logger.log(year2);
string = Company + ID + "-"+ "" + julian + "/" + year2 + "-";
return string;
}
Modification points:
When I saw your script, I noticed that SpreadsheetApp.openById is used as the global. By this, when your custom function is run, SpreadsheetApp.openById is run. So, such error occurs. I think that this is the reason of your issue.
When you want to use both script in your Google Apps Script, how about the following modification?
Modified script:
function when(e) {
// These scripts are included in a function.
var ss1 = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var dukeid = "1WGbEo1Xr99HwHY_4ZaeTRIgCOuNcjVfqCzZx4dcQX4I"
var duke = SpreadsheetApp.openById(dukeid);
var totalstockd = duke.getSheetByName("Total Stock").getRange(2, 3, 2500, 7).getValues();
var avmid = "1a6bm2O_iljHZUoF2BhYeyxUT13tB06-JJCYeYCZZ10Q"
var avm = SpreadsheetApp.openById(avmid);
var totalstocka = avm.getSheetByName("Total Stock").getRange(2, 3, 1000, 7).getValues();
var activeCell = e.range;
var val = activeCell.getValue();
var r = activeCell.getRow();
var c = activeCell.getColumn();
var ssName = activeCell.getSheet().getName();
if (ssName == "General Information" && (r == 3 || r == 6) && c == 3) {
var rescell = ss1.getRange(r, 6);
var unitcell = ss1.getRange(r, 7);
rescell.clearContent();
if (val[0] == "A") {
var result = sumalt(val, totalstocka, unitcell);
rescell.setValue(result);
} else {
var result = sumalt(val, totalstockd, unitcell);
rescell.setValue(result);
}
} else {
console.log("No Edit");
}
}
function QREF(Company, ID) {
var td = new Date().valueOf();
var year = new Date().getFullYear();
var hd = new Date(year, 0, 0).valueOf();
var year2 = year - 2000
var sec = 1000;
var min = 60 * sec;
var hour = 60 * min;
var day = 24 * hour;
var diff = td - hd;
var julian = Math.floor(diff / day);
Logger.log(year2);
string = Company + ID + "-" + "" + julian + "/" + year2 + "-";
return string;
}
By this modification, when QREF() is run as the custom function, SpreadsheetApp.openById is not run. By this, such error can be removed.
Note:
If you are using the following script at other function, please be careful this. In that case, please include the script to the function. Or, please include the following script as new function, and call the function from other function.
var ss1 = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var dukeid = "1WGbEo1Xr99HwHY_4ZaeTRIgCOuNcjVfqCzZx4dcQX4I"
var duke = SpreadsheetApp.openById(dukeid);
var totalstockd = duke.getSheetByName("Total Stock").getRange(2, 3, 2500, 7).getValues();
var avmid = "1a6bm2O_iljHZUoF2BhYeyxUT13tB06-JJCYeYCZZ10Q"
var avm = SpreadsheetApp.openById(avmid);
var totalstocka = avm.getSheetByName("Total Stock").getRange(2, 3, 1000, 7).getValues();

Wanting to update an Adobe CS dropdown list from my google sheet

Here is what I wrote for my Google Form to pull data from my Gsheet. But want to pull the same information from the gsheet to an Adobe PDF? Is that even possible. I wanted to use it to make a drop down where it pulls names from a gsheet.
var ssID = "enter ssID";
var formID = "enter form ID ";
var wsData = SpreadsheetApp.openById(ssID).getSheetByName("data");
var form = FormApp.openById(formID);
function main(){
var labels = wsData.getRange(1, 1,1,wsData.getLastColumn()).getValues()[0];
labels.forEach(function(label,i){
var options = wsData
.getRange(2, i + 1,wsData.getLastRow()-1,1)
.getValues()
.map(function(o){ return o[0] });
updateDropDownUsingTitle(label,options)
});
}
function updateDropDownUsingTitle(title,values) {
var items = form.getItems();
var titles = items.map(function(item){
return item.getTitle();
});
var pos = titles.indexOf(title);
var item = items[pos];
var itemID = item.getId();
updateDropdown(itemID,values);
}
function updateDropdown(id, values) {
var item = form.getItemById(id);
item.asListItem().setChoiceValues(values);
}

We're sorry, a server error occurred. Please wait a bit and try again. (line 63, file "Code")

Thank you in advance for helping.
I am trying to convert the most recent submitted data from Google Form/Google sheets to a "template" Google doc. Basically, when a user submit a form, it will convert the data from Google Sheet and create a new Google Doc.
Side note: Im not really a coder.. I found the base script online and tried to modified it accordingly. I would greatly appreciate a step by step if possible?
AGAIN, THANK YOU SO MUCH
function createDocument() {
var headers = Sheets.Spreadsheets.Values.get('SHEET-ID', 'A1:AU1');
var tactics = Sheets.Spreadsheets.Values.get('SHEET-ID', 'A2:AU2');
var templateId = 'DOCTEMPLATE-ID';
for(var i = 0; i < tactics.values.length; i++){
var Fclient = tactics.values[i][0];
var Lclient = tactics.values[i][1];
var birthday = tactics.values[i][2];
var profession = tactics.values[i][3];
var email = tactics.values[i][4];
var phone = tactics.values[i][5];
var whatsapp = tactics.values[i][6];
var preferredcontact = tactics.values[i][7];
var UScitizen = tactics.values[i][8];
var Ocitizen = tactics.values[i][9];
var Tsapre = tactics.values[i][10];
var Pairplane = tactics.values[i][11];
var Photelamen = tactics.values[i][12];
var FFlyer = tactics.values[i][13];
var hotelloy = tactics.values[i][14];
var vistedcountries = tactics.values[i][15];
var smoke = tactics.values[i][16];
var allergies = tactics.values[i][17];
var Othermed = tactics.values[i][18];
var addANOTHER = tactics.values[i][19];
var emergencyname = tactics.values[i][20];
var emergencyphone = tactics.values[i][21];
var emergencyrelation = tactics.values[i][22];
var emergencyname2 = tactics.values[i][23];
var emergencyphone2 = tactics.values[i][24];
var emergencyrelation2 = tactics.values[i][25];
var comptravelmag = tactics.values[i][26];
var secondaryFname = tactics.values[i][27];
var secondaryLname = tactics.values[i][28];
var secondarybirthday = tactics.values[i][29];
var secondaryprofession = tactics.values[i][30];
var secondaryemail = tactics.values[i][31];
var secondaryphone = tactics.values[i][32];
var secondarywhatsapp = tactics.values[i][33];
var secondarypreferredcontact = tactics.values[i][34];
var secondaryUScitizen = tactics.values[i][35];
var secondaryOcitizen = tactics.values[i][36];
var secondaryTsapre = tactics.values[i][37];
var secondaryPairplane = tactics.values[i][38];
var secondaryPhotelamen = tactics.values[i][39];
var secondaryFFlyer = tactics.values[i][40];
var secondaryhotelloy = tactics.values[i][41];
var secondaryvistedcountries = tactics.values[i][42];
var secondarysmoke = tactics.values[i][43];
var secondaryallergies = tactics.values[i][44];
var secondaryOthermed = tactics.values[i][45];
var timestamp = tactics.values[i][46];
//Make a copy of the template file
var documentId = DriveApp.getFileById(templateId).makeCopy().getId();
//Rename the copied file
DriveApp.getFileById(documentId).setName('Basic Information: ' + Lclient + 'test');
//Get the document body as a variable.
var body = DocumentApp.openById(documentId).getBody(); **ERROR HERE**
//Insert the supplier name
body.replaceText('{{Fcilent}}', Fclient);
body.replaceText('{{Lcilent}}', Lclient);
body.replaceText('{{birthday}}', birthday);
body.replaceText('{{profession}}', profession);
body.replaceText('{{email}}', email);
body.replaceText('{{phone}}', phone);
body.replaceText('{{whatsapp}}', whatsapp);
body.replaceText('{{preferredcontact}}', preferredcontact);
body.replaceText('{{UScitizen}}', UScitizen);
body.replaceText('{{Ocitizen}}', Ocitizen);
body.replaceText('{{Tsapre}}', Tsapre);
body.replaceText('{{Pairplane}}', Pairplane);
body.replaceText('{{Photelamen}}', Photelamen);
body.replaceText('{{FFlyer}}', FFlyer);
body.replaceText('{{hotelloy}}', hotelloy);
body.replaceText('{{vistedcountries}}', vistedcountries);
body.replaceText('{{smoke}}', smoke);
body.replaceText('{{allergies}}', allergies);
body.replaceText('{{Othermed}}', Othermed);
body.replaceText('{{addANOTHER}}', addANOTHER);
body.replaceText('{{emergencyname}}', emergencyname);
body.replaceText('{{emergencyphone}}', emergencyphone);
body.replaceText('{{emergencyrelation}}', emergencyrelation);
body.replaceText('{{emergencyname2}}', emergencyname2);
body.replaceText('{{emergencyphone2}}', emergencyphone2);
body.replaceText('{{emergencyrelation2}}', emergencyrelation2);
body.replaceText('{{comptravelmag}}', comptravelmag);
body.replaceText('{{secondaryFname}}', secondaryFname);
body.replaceText('{{secondaryLname}}', secondaryLname);
body.replaceText('{{secondarybirthday}}', secondarybirthday);
body.replaceText('{{secondaryprofession}}', secondaryprofession);
body.replaceText('{{secondaryemail}}', secondaryemail);
body.replaceText('{{secondaryphone}}', secondaryphone);
body.replaceText('{{secondarywhatsapp}}', secondarywhatsapp);
body.replaceText('{{secondarypreferredcontact}}', secondarypreferredcontact);
body.replaceText('{{secondaryUScitizen}}', secondaryUScitizen);
body.replaceText('{{secondaryOcitizen}}', secondaryOcitizen);
body.replaceText('{{secondaryTsapre}}', secondaryTsapre);
body.replaceText('{{secondaryPairplane}}', secondaryPairplane);
body.replaceText('{{secondaryPhotelamen}}', secondaryPhotelamen);
body.replaceText('{{secondaryFFlyer}}', secondaryFFlyer);
body.replaceText('{{secondaryhotelloy}}', secondaryhotelloy);
body.replaceText('{{secondaryvistedcountries}}', secondaryvistedcountries);
body.replaceText('{{secondarysmoke}}', secondarysmoke);
body.replaceText('{{secondaryallergies}}', secondaryallergies);
body.replaceText('{{secondaryOthermed}}', secondaryOthermed);
body.replaceText('{{timestamp}}', timestamp);
//Append tactics
parseTactics(headers.values[0], tactics.values[i], body);
}
}
function parseTactics(headers, tactics, body){
for(var i = 1; i < tactics.length; i++){
{tactics[i] != '' &&
body.appendListItem(headers[i] + ' | ' + tactics[i] + ' OTHER').setGlyphType(DocumentApp.GlyphType.BULLET);
}
}
}
Error: "We're sorry, a server error occurred. Please wait a bit and try again. (line 63, file "Code")"
I expected the script to generate a new google doc from the data sheet as it is being submitted on google form.
I think your pretty close. Here's an example I did.
First, I created a function to generate some data for myself.
function testData() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getActiveSheet();
sh.clearContents();
var rg=sh.getRange(1,1,10,10);
var vA=rg.getValues();
for(var i=0;i<vA.length;i++) {
for(var j=0;j<vA[i].length;j++) {
vA[i][j]=Utilities.formatString('row: %s - col: %s',i+1,j+1);
}
}
rg.setValues(vA);
}
The above function creates a sheet that looks like this:
The Template File Looks like this:
And after running this code:
function createDoc(){
var spreadsheetId='spreadsheet Id';
var templateId='template Id';
var data=Sheets.Spreadsheets.Values.get(spreadsheetId,'Sheet177!A1:J2');//range include sheet name
var docId=DriveApp.getFileById(templateId).makeCopy('Test').getId();
var body=DocumentApp.openById(docId).getBody();
for(var i=0;i<data.values.length;i++) {
for(var j=0;j<data.values[i].length;j++) {
var s=Utilities.formatString('{{col%s-%s}}',i+1,j+1);
body.replaceText(s,data.values[i][j]);
}
}
}
There appears in the same folder another file named test that looks like this:
I must say that sure is a simple way to get data.
I'm kind of wondering if perhaps you simply didn't authenticate the program in the script editor.