How to remove limit in creating folder in Google Drive through Spreadsheet - google-apps-script

I wanted to create a bulk of folders in my google drive using scripts in google spreadsheet. Fortunately, I have found the script I have been looking for. However, upon executing the script, it gave a notice that (I forgot the exact message) I have reached the maximum number of folders to create. So it just stops. Here is the code. I hope someone could tell me how can I or what should I change for it to create folders as required.
function onOpen() { //This is the new standard script for the onOpen trigger that creates a menu item.
var ui = SpreadsheetApp.getUi();
// Or DocumentApp or FormApp.
ui.createMenu('GDrive')
.addItem('Create new Folders', 'crtGdriveFolder')
.addToUi();
}
function crtGdriveFolder() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var levelInput = Browser.inputBox('input Level', Browser.Buttons.OK_CANCEL);
var Level = levelInput * 2 + 1;
var numRows = sheet.getLastRow(); // Number of rows to process
var dataRange = sheet.getRange(3, Number(Level)-1, numRows, Number(Level)); //startRow, startCol, endRow, endCol
var data = dataRange.getValues();
var parentFolderID = new Array();
for(var i in data)
{
parentFolderID[i] = data [i][0];
if (data [i][0] == "")
{
parentFolderID[i] = parentFolderID[i-1];
}
}
for(var i in data){
if (data [i][1] !== "")
{
var theParentFolder = DriveApp.getFolderById(parentFolderID[i]);
var folderName = data[i][1];
var theChildFolder = theParentFolder.createFolder(folderName);
// Utilities.sleep(100);
var newFolderID = sheet.getRange(Number(i)+3,Number(Level)+1);
var folderIdValue = theChildFolder.getId();
newFolderID.setValue(folderIdValue);
var addLink = sheet.getRange(Number(i)+3,Number(Level));
var value = addLink.getDisplayValue();
addLink.setValue('=hyperlink("https://drive.google.com/corp/drive/folders/'+ folderIdValue +'","' + value + '")');
}
}
}```
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/QKKLr.jpg

Related

Update a cell and return PDF file of the sheet

I've this spreadsheet that is of 2 sheets, Data nd Report.
function doPost(e) {
var DATA_SHEET = "Data";
var REPORT_SHEET = "Report";
var FILE_Id = "1sXSWMQfPkkwDS4lsSpnV2y54lhKFpdeY8brqyGtuc_k";
// Prevent concurrent access overwritting data
// we want a public lock, one that locks for all invocations
var lock = LockService.getPublicLock();
lock.waitLock(30000); // wait 30 seconds before conceding defeat.
// As we are passing JSON in the body, we need to unpairse it
var jsonString = e.postData.getDataAsString();
e.parameter = JSON.parse(jsonString);
try {
// next set where we write the data - you could write to multiple/alternate destinations
// var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var doc = SpreadsheetApp.openById(FILE_Id);
var sheet = doc.getSheetByName(DATA_SHEET);
var report = doc.getSheetByName(REPORT_SHEET);
// we'll assume header is in row 1 but you can override with header_row in GET/POST data
var headRow = e.parameter.header_row || 1;
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
var lastRow = sheet.getLastRow()
var nextRow = lastRow + 1; // get next row
var row = [];
if(lastRow < 10){
RefID = "PRF.00" + lastRow
} else {
if(lastRow < 100){
RefID = "PRF..0" + lastRow
} else {
RefID = "PRF.." + lastRow
}
}
// loop through the header columns
for (i in headers){
if (headers[i] == "Ref"){ // special case if you include a 'Timestamp' column
row.push(RefID);
} else { // else use header name to get data
if (headers[i] == "Timestamp"){ // special case if you include a 'Timestamp' column
row.push(new Date());
} else { // else use header name to get data
row.push(e.parameter[headers[i]]);
}
}
}
// more efficient to set values as [][] array than individually
sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);
/*********************************************/
// report.getRange("D4").setValue(RefID);
// Need to create the PDF here and send it back to the client
/*********************************************/
// return json success results
return ContentService
.createTextOutput(JSON.stringify({"result":"success", "row": nextRow}))
.setMimeType(ContentService.MimeType.JSON);
} catch(e){
// if error return this
return ContentService
.createTextOutput(JSON.stringify({"result":"error", "error": e}))
.setMimeType(ContentService.MimeType.JSON);
} finally { //release lock
lock.releaseLock();
}
}
The Report sheet looks like this:
And the Data sheet looks like this:
What I'm trying to do is:
[Done] Receiving data from client and post in the Data sheet, with assigning RefID and Timestamp which is done correctly.
[Done] Update the data in the merged cells (D4:F4) at the Report sheet with the latest RefID that had been added, I worked it withreport.getRange("D4").setValue(RefID);
[No idea how to make it] Once step 2 is done, some vlookup statements are working at the Report sheet, I want to generate a PDF from this sheet and send it back to the client.
UPDATE
I tried this to get the PDF, but did not work, it created copy of the sheet, but failed in converting the vlookup merged cells into text, and failed to generate the pdf file:
function printPDF() {
var file = SpreadsheetApp.openById(FILE_Id);
var sourceSheet = file.getSheetByName(REPORT_SHEET);
var folder = DriveApp.getFolderById(FOLDER_Id);
//Copy whole spreadsheet
var destSpreadsheet = SpreadsheetApp.open(DriveApp.getFileById(FILE_Id).makeCopy("tmp_convert_to_pdf", folder))
//delete redundant sheets
var sheets = destSpreadsheet.getSheets();
for (i = 0; i < sheets.length; i++) {
if (sheets[i].getSheetName() != REPORT_SHEET){
destSpreadsheet.deleteSheet(sheets[i]);
}
}
var destSheet = destSpreadsheet.getSheets()[0];
//replace cell values with text (to avoid broken references)
var sourceRange = sourceSheet.getRange(1,1,20,8);
var sourcevalues = sourceRange.getValues();
var destRange = destSheet.getRange(1, 1, 20, 8);
destRange.setValues(sourcevalues);
//save to pdf
var theBlob = destSpreadsheet.getBlob().getAs('application/pdf').setName(REPORT);
var newFile = folder.createFile(theBlob);
//Delete the temporary sheet
DriveApp.getFileById(destSpreadsheet.getId()).setTrashed(true);
}
Modification points:
If you want to make the additional script of printPDF() work correctly, please put SpreadsheetApp.flush() before the blob is retrieved from Spreadsheet.
In the case of the Google Docs (Document, Spreadsheet and Slides), when the blob is retrieved from the file, the format is automatically changed to PDF format. It seems that this is the current specification.
When above points are reflected to your script, it becomes as follows.
Modified script:
From:
var theBlob = destSpreadsheet.getBlob().getAs('application/pdf').setName(REPORT);
var newFile = folder.createFile(theBlob);
To:
SpreadsheetApp.flush(); // Added
var theBlob = destSpreadsheet.getBlob().setName(REPORT); // Modified. This is the same with destSpreadsheet.getBlob().getAs('application/pdf').setName(REPORT)
var newFile = folder.createFile(theBlob);
Then your full code be as:
function printPDF(RefID) {
var file = SpreadsheetApp.openById(FILE_Id);
var sourceSheet = file.getSheetByName(REPORT_SHEET);
sourceSheet.getRange("D4").setValue(RefID);
var folder = DriveApp.getFolderById(FOLDER_Id);
//Copy whole spreadsheet
var destSpreadsheet = SpreadsheetApp.open(DriveApp.getFileById(FILE_Id).makeCopy("tmp_convert_to_pdf", folder))
// Copy sheet data into values to avoid reference issues
var destSheet = destSpreadsheet.getSheetByName(REPORT_SHEET);
var sourceRange = sourceSheet.getRange(1,1,destSheet.getMaxRows(), destSheet.getMaxColumns());
var sourcevalues = sourceRange.getValues();
var destRange = destSheet.getRange(1, 1, destSheet.getMaxRows(), destSheet.getMaxColumns());
destRange.setValues(sourcevalues);
//delete redundant sheets
var sheets = destSpreadsheet.getSheets();
for (i = 0; i < sheets.length; i++) {
if (sheets[i].getSheetName() != REPORT_SHEET){
destSpreadsheet.deleteSheet(sheets[i]);
}
}
//save to pdf
SpreadsheetApp.flush(); // Added
var theBlob = destSpreadsheet.getBlob().setName(REPORT); // Modified. This is the same with
// destSpreadsheet.getBlob().getAs('application/pdf').setName(REPORT)
var newFile = folder.createFile(theBlob);
//Delete the temporary sheet
DriveApp.getFileById(destSpreadsheet.getId()).setTrashed(true);
}
Reference:
flush()
getBlob().getAs('application/pdf') will not work. You need to use a Google API for converting a sheet to PDF.
You need to do something along the following lines:
const url = `https://docs.google.com/spreadsheets/d/${FILE_Id}/export?exportFormat=pdf&format=pdf`;
const options = {
headers: {
Authorization: `Bearer ${ScriptApp.getOAuthToken()}`
}
};
const blob = UrlFetchApp.fetch(url, options).setName(`${REPORT}`);

App script to create folders fails to run in shared drive

Google app script newbie here. I found this code which helps create folders in my personal Google drive with using inputs from Google sheet (credit: Google Sheet Community on Youtube). However, when I tried to recreate this app in a shared Google drive, it failed to run and kept creating folders in my personal drive instead. Is there anything I can change about the code to make it work in the shared drive environment instead of my own?
Thanks a lot!
var ui = SpreadsheetApp.getUi();
// Or DocumentApp or FormApp.
ui.createMenu('GDrive')
.addItem('Create new Folders', 'crtGdriveFolder')
.addToUi(); }
function crtGdriveFolder() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = sheet.getLastRow(); // Number of rows to process
var maxRows = Math.min(numRows,20); //Limit the number of rows to prevent enormous number of folder creations
var folderid = sheet.getRange("C2").getValue();
var root = sheet.getRange("D2").getValue();
var dataRange = sheet.getRange(startRow, 1, maxRows, 2); //startRow, startCol, endRow, endCol
var data = dataRange.getValues();
var folderIterator = DriveApp.getFoldersByName(folderid); //get the file iterator
if(!folderIterator.hasNext()) { SpreadsheetApp.getActiveSpreadsheet().toast('Folder not found!');
return; }
var parentFolder = folderIterator.next();
if(folderIterator.hasNext()) {
SpreadsheetApp.getActiveSpreadsheet().toast('Folder has a non-unique name!');
return; }
for (i in data) {
var row = data[i];
var name = row[0]; // column A
var desc = row[1]; // column B
if(root == "N" && name != "") {
var idNewFolder = parentFolder.createFolder(name).setDescription(desc).getId(); Utilities.sleep(100);
var newFolder = DriveApp.getFolderById(idNewFolder);
} if(root == "Y" && name != "") {
var idNewFolder = DriveApp.createFolder(name).setDescription(desc).getId();
Utilities.sleep(100);
var newFolder = DriveApp.getFolderById(idNewFolder);
}
}
}
DriveApp creates folders by default in your own Drive
If you want to create a folder on a shared Drive instead, you need to use the the Advanced Drive Service based on the Drive API
Make sure to enable the advanced service before using
Use the advanced option {supportsAllDrives : true}
Specify the id of the shared Drive as parents
A sample how to create a folder on the shared drive based on your code:
} if(root == "Y" && name != "") {
var optionalArgs={supportsAllDrives: true};
var resource = {
title: name,
description: desc,
mimeType: "application/vnd.google-apps.folder",
parents:[{
"id": "ID OF SHARED DRIVE"
}]
}
var idNewFolder = Drive.Files.insert(resource, null, optionalArgs).id;
Utilities.sleep(100);
var newFolder = DriveApp.getFolderById(idNewFolder);
}

Big query API has not been used in this project or has been disabled

I am running code that takes images from my drive and puts them into google slides. Also I am trying to export data from big query into a table in the same google slides doc. I keep getting this error though, but the API is enabled?
The issue seems to be with this line:
var queryResults = BigQuery.Jobs.query(request, projectId);
Also for some reason the big query data doesn't come into google slides as a table
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Custom Menu')
.addItem('Generate Level B', 'showSidebar')
.addToUi();
}
function showSidebar() {
var ui = HtmlService.createHtmlOutputFromFile('sidebar')
.setTitle('Generate Level B');
SpreadsheetApp.getUi().showSidebar(ui);
}
function showPrompt() {
var ui = SpreadsheetApp.getUi();
var result = ui.prompt(
'Generate custom company slide',
'Please enter the ticker symbol for the company:',
ui.ButtonSet.OK_CANCEL);
// Process the user's response.
var button = result.getSelectedButton();
var text = result.getResponseText();
if (button == ui.Button.OK) {
// User clicked "OK".
mergeSlide(text);
} else if (button == ui.Button.CANCEL) {
// User clicked "Cancel".
return;
} else if (button == ui.Button.CLOSE) {
// User clicked X in the title bar.
return;
}
}
function test() {
mergeSlide("DSYJ.J", "");}
function mergeSlide(tickerSymbol,companyName) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var lastRow = sheet.getLastRow();
var dataTicker = flatten(sheet.getRange(3, 1, lastRow-2, 1).getValues());
var dataName = flatten(sheet.getRange(3, 2, lastRow-2, 1).getValues());
var dataDesc = flatten(sheet.getRange(3, 3, lastRow-2, 1).getValues());
//Find index based on ticker/name
if(tickerSymbol != ""){
var index = dataTicker.indexOf(tickerSymbol);
var companyDesc = dataDesc[index];
var companyName = dataName[index];
}else if(companyName != ""){
var index = dataName.indexOf(companyName);
var companyDesc = dataDesc[index];
var tickerSymbol = dataTicker[index];
}else{
return;
}
var slideUrl = DriveApp.getFileById("xxxx").makeCopy(companyName).getUrl();
var slide = SlidesApp.openByUrl(slideUrl);
var slides = slide.getSlides();
//Slide1
var shapesSlide1 = slides[0].getShapes();
shapesSlide1[0].getText().setText(companyName);
//Slide2
var shapesSlide2 = slides[1].getShapes();
shapesSlide2[0].getText().setText(companyDesc);
//Slide3
// Replace this value with the project ID listed in the Google Cloud Platform project.
var projectId = 'vital-platform-791';
var sqlQuery = 'SELECT Price FROM [vital-platform-791.feeds.chrome_blue_button_valuegrid_lookup] LIMIT 5';
var request = {
query: sqlQuery
};
var queryResults = BigQuery.Jobs.query(request, projectId);
var jobId = queryResults.jobReference.jobId;
// Check on status of the Query Job.
var sleepTimeMs = 500;
while (!queryResults.jobComplete) {
Utilities.sleep(sleepTimeMs);
sleepTimeMs *= 2;
queryResults = BigQuery.Jobs.getQueryResults(projectId, jobId);
}
// Get all the rows of results.
var rows = queryResults.rows;
while (queryResults.pageToken) {
queryResults = BigQuery.Jobs.getQueryResults(projectId, jobId, {
pageToken: queryResults.pageToken
});
rows = rows.concat(queryResults.rows);
}
if (rows) {
// Get the headers.
var headers = queryResults.schema.fields.map(function(field) {
return field.name;
});
// Get the results.
var data = new Array(rows.length);
for (var i = 0; i < rows.length; i++) {
var cols = rows[i].f;
data[i] = new Array(cols.length);
for (var j = 0; j < cols.length; j++) {
data[i][j] = cols[j].v;
}
}
var table = slides[2].insertTable(rows.length+1, headers.length);
//Fill up the table header
for(var m = 0; m< headers.length; m++){
table.getCell(0,m).getText().setText(headers[m]).getTextStyle().setForegroundColor(255,0,86).setBold(true);
}
//Fill up rest of table
for(var k = 1; k< rows.length+1; k++){
for(var m = 0; m< headers.length; m++){
table.getCell(k,m).getText().setText(data[k-1][m]);
}
}
}
//Slide4
var shapeSlide4 = slides[3].getShapes();
var priceChangeImage = DriveApp.getFilesByName("Price Change_"+tickerSymbol+".png").next();
var newImage4 = shapeSlide4[0].replaceWithImage(priceChangeImage);
newImage4.setWidth(650);
newImage4.alignOnPage(SlidesApp.AlignmentPosition.HORIZONTAL_CENTER);
//Slide5
var shapeSlide5 = slides[4].getShapes();
var earningsRevisionsImage = DriveApp.getFilesByName("Earnings Revisions_"+tickerSymbol+".png").next();
var newImage5 = shapeSlide5[0].replaceWithImage(earningsRevisionsImage);
newImage5.setWidth(650);
newImage5.alignOnPage(SlidesApp.AlignmentPosition.HORIZONTAL_CENTER);
//Slide6
var shapeSlide6 = slides[5].getShapes();
var FgpeImage = DriveApp.getFilesByName("F-GPE_"+tickerSymbol+".png").next();
var newImage6 = shapeSlide6[0].replaceWithImage(FgpeImage);
newImage6.setWidth(650);
newImage6.alignOnPage(SlidesApp.AlignmentPosition.HORIZONTAL_CENTER);
newSlideNotify(slideUrl);
}
// Takes and array of arrays matrix and return an array of elements.
function flatten(arrayOfArrays){
return [].concat.apply([], arrayOfArrays);
}
function newSlideNotify(url) {
var htmlOutput = HtmlService
.createHtmlOutput('<p style="font-family:Arial;font-size:13px;">A Level B report has been created for the company that you have selected.<br><br>This new file has been placed in the same folder with the Slide Template.<br><br></p>Open Level B')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setWidth(500)
.setHeight(150);
SpreadsheetApp.getUi().showModalDialog(htmlOutput, 'Level B Generated!');
}
function getList() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var lastRow = sheet.getLastRow();
var dataTicker = flatten(sheet.getRange(3, 1, lastRow-2, 1).getValues());
var dataName = flatten(sheet.getRange(3, 2, lastRow-2, 1).getValues());
return [dataTicker,dataName];
}
You need to enable the Advanced Service for BigQuery in your Google-Apps-script:
In this link about the BigQuery Service:
Note: This is an advanced service that must be enabled before use.
...which redirects you to this link where it explains how to enable advanced services:
In the script editor, select Resources > Advanced Google services....
Click the on/off switch next to the service you want to use (in your case BigQuery API).
Click OK.
The next steps in the link explain you how to enable the API in the GOOGLE CLOUD PLATFORM Console (which I assume you have already done as you said that the API is already enabled)
Does the error look like this?
Access Not Configured. BigQuery API has not been used in project
5622793721 before or it is disabled. Enable it
If so, the problem is that you need to go to your Dashboard and enable it.
Open your script file
Go to Resources > Advanced Google Services
Notice the message saying These services must also be enabled in the Google API Console.
Click the link where it says Google API Console
After searching for 'bigquery', do not select the one called Bigquery API. You are looking for the one called BigQuery Data Transfer API
Enable it
Run your code again to see if it works now
You may have to activate your email to the Analytics user management.

Preserve formula references when printing a single Google Sheets sheet to PDF

I want to accomplish the following:
Make a menu with a print to PDF button.
Have that button export a PDF to with the same name and same destination as the google sheet.
This works well, but the script I found I need to change, because most people print to PDF by making a temporary copy of the sheet, printing, and finally deleting the temporary copy.
I have references from other sheets in my original document that ends up printed as #REF! values because only the one sheet gets copied and printed, not my whole document.
How can i make this process include baking the formulas as text?
CODE FOR PRINTING:
function onOpen() {
var submenu = [{name: "Save PDF", functionName: "generatePdf"}];
SpreadsheetApp.getActiveSpreadsheet().addMenu('Export', submenu);
}
function generatePdf() {
// Get active spreadsheet.
var sourceSpreadsheet = SpreadsheetApp.getActive();
// Get active sheet.
var sheets = sourceSpreadsheet.getSheets();
var sheetName = sourceSpreadsheet.getActiveSheet().getName();
var sourceSheet = sourceSpreadsheet.getSheetByName(sheetName);
// Set the output filename as sheetName.
var pdfName = sheetName;
// Get folder containing spreadsheet to save pdf in.
var parents = DriveApp.getFileById(sourceSpreadsheet.getId()).getParents();
if (parents.hasNext()) {
var folder = parents.next();
}
else {
folder = DriveApp.getRootFolder();
}
// Copy whole spreadsheet.
var destSpreadsheet = SpreadsheetApp.open(DriveApp.getFileById(sourceSpreadsheet.getId()).makeCopy("tmp_convert_to_pdf", folder))
// Delete redundant sheets.
var sheets = destSpreadsheet.getSheets();
for (i = 0; i < sheets.length; i++) {
if (sheets[i].getSheetName() != sheetName){
destSpreadsheet.deleteSheet(sheets[i]);
}
}
var destSheet = destSpreadsheet.getSheets()[0];
// Replace cell values with text (to avoid broken references).
var sourceRange = sourceSheet.getRange(1, 1, sourceSheet.getMaxRows(), sourceSheet.getMaxColumns());
var sourcevalues = sourceRange.getValues();
var destRange = destSheet.getRange(1, 1, destSheet.getMaxRows(), destSheet.getMaxColumns());
destRange.setValues(sourcevalues);
// Save to pdf.
var theBlob = destSpreadsheet.getBlob().getAs('application/pdf').setName(pdfName);
var newFile = folder.createFile(theBlob);
// Delete the temporary sheet.
DriveApp.getFileById(destSpreadsheet.getId()).setTrashed(true);
}
CODE FOR CONVERTING FORMULAS TO TEXT:
function formulasAsText() {
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
for (var k = 0; k < sheets.length; k++) {
var range = sheets[k].getDataRange();
var values = range.getValues();
var formulas = range.getFormulas();
for (var i = 0; i < values.length; i++) {
for (var j = 0; j < values[0].length; j++) {
values[i][j] = formulas[i][j] ? "'" + formulas[i][j] : values[i][j];
}
}
range.setValues(values);
}
}
To maintain formula references, you need to modify the formulasAsText() function to accept an input, and also not worry about writing a formula if one is found. This input could be a spreadsheet ID - i.e. the id of the temporary copy - or it could be an array of Sheet objects.
Once you have made these two modifications, you would call the function prior to deleting the non-desired sheets in the temporary copy:
/**
* #param Sheet[] wbSheets An array of Sheets to operate on.
* #param String toPreserve The name of the sheet which should be preserved.
*/
function preserveFormulas(wbSheets, toPreserve) {
if(!wbSheets || !wbSheets.length || !toPreserve)
throw new Error("Missing arguments.");
wbSheets.forEach(function (sheet) {
if ( sheet.getName() === toPreserve ) {
var range = sheet.getDataRange();
// Serialize the cell's current value, be it static or derived from a formula.
range.setValues(range.getValues());
}
});
}
Finished my script. Here is what i ended up with.
function onOpen() {
var submenu = [{name:"Save PDF", functionName:"generatePdf"}];
SpreadsheetApp.getActiveSpreadsheet().addMenu('Export', submenu);
}
function hideSheets() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet1 = ss.getSheetByName("sheet1");
var sheet2 = ss.getSheetByName("PRINT SHEET");
var sheet3 = ss.getSheetByName("sheet3");
var sheet4 = ss.getSheetByName("sheet4");
var sheet5 = ss.getSheetByName("sheet5");
var sheet6 = ss.getSheetByName("sheet6");
var sheet7 = ss.getSheetByName("sheet7");
sheet1.hideSheet();
sheet3.hideSheet();
sheet4.hideSheet();
sheet5.hideSheet();
sheet6.hideSheet();
sheet7.hideSheet();
}
function showSheets() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet1 = ss.getSheetByName("sheet1");
var sheet2 = ss.getSheetByName("PRINT SHEET");
var sheet3 = ss.getSheetByName("sheet3");
var sheet4 = ss.getSheetByName("sheet4");
var sheet5 = ss.getSheetByName("sheet5");
var sheet6 = ss.getSheetByName("sheet6");
var sheet7 = ss.getSheetByName("sheet7");
sheet1.showSheet();
sheet3.showSheet();
sheet4.showSheet();
sheet5.showSheet();
sheet6.showSheet();
sheet7.showSheet();
}
function generatePdf() {
// Get active spreadsheet.
var sourceSpreadsheet = SpreadsheetApp.getActive();
// Get active sheet.
var sheets = sourceSpreadsheet.getSheets();
var sheetName = sourceSpreadsheet.getActiveSheet().getName();
var sourceSheet = sourceSpreadsheet.getSheetByName(sheetName);
// Set the output filename as BID and number (from cell C4).
var pdfName = "BID " + sheets[0].getRange("C4").getValue() + ".pdf";
var ui = SpreadsheetApp.getUi();
// Get folder containing spreadsheet to save pdf in.
var parents = DriveApp.getFileById(sourceSpreadsheet.getId()).getParents();
if (parents.hasNext()) {
var folder = parents.next();
}
else {
folder = DriveApp.getRootFolder();
}
hideSheets();
// Save to pdf.
var theBlob = sourceSpreadsheet.getBlob().getAs('application/pdf').setName(pdfName);
var newFile = folder.createFile(theBlob);
showSheets();
ui.alert('Export finished');
}
Thanks.

Google App Script - getCommenter

I'm brand new to Google Apps Script, and I'm trying to create a simple spreadsheet that will allow me to share files by user email through a single spreadsheet.
I have written the following script, which will allow me to add editors and viewers, but not commenters.
I keep getting an error that states that the function addCommenter cannot be found in object spreadsheet.
function shareSheet () {
var ss = SpreadsheetApp.getActiveSpreadsheet();
ss.toast('Updating access level...');
var sheet = ss.getSheets()[0];
var lastRow = sheet.getLastRow();
var range1 = sheet.getRange (3,1, lastRow,9);
var data = range1.getValues();
for (var i= 0; i < data.length; i++) {
var row = data [i];
var accessLevel = row [5];
var values = row [8];
var ss2 = SpreadsheetApp.openById(values);
var values2 = row [4];
// Add new editor
if (accessLevel == 'Edit') {
var addEditors = ss2.addEditor(values2);
}
// Add new viewer
if (accessLevel == 'View'){
var addViewers = ss2.addViewer(values2);
}
// Add new commenter
if (accessLevel == 'Comment') {
var addCommenters = ss2.addCommenter(values2);
}
}
}
The Spreadsheet object does not support the addCommentor() method. You should use DriveApp service instead.
DriveApp.getFileById(id).addCommenter(emailAddress)