Share issue with script - google-apps-script

I have this script I am using to make a copy of a sheet and then send me that copy thru email as a xslx file, if I have the sheet set for share to anyone with a link the script works great, but if I have it set to specific people it runs but gives a Value# instead of the data on the page. the page I am trying to send is a query importrange formula pulling the data on to the sheet. any help would be greatly appreciated.
enter code herefunction emailExcel() {
var mailTo, subject, body, id, sheetNum, sh, sourceSS, copySS, file, url,token, response;
mailTo = 'elder1104#gmail.com';
subject = 'subject';
body = 'text_in_body';
id = '1eI-p0nodA4zqP3fsxP5P6iR6gyvSIGRZDMaQSGkb2ds';
sheetNum = 2;
sourceSS = SpreadsheetApp.openById(id);
copySS = sourceSS.copy('copy of ' + sourceSS.getName());
sh = copySS.getSheets()[sheetNum];
sh.getDataRange().setValues(sh.getDataRange().getDisplayValues())
copySS.getSheets()
.forEach(function (sh, i) {
if(i != sheetNum) copySS.deleteSheet(sh);
})
file = Drive.Files.get(copySS.getId());
url = file.exportLinks[MimeType.MICROSOFT_EXCEL];
token = ScriptApp.getOAuthToken();
response = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
MailApp.sendEmail(mailTo, subject, body, {
attachments: [response.getBlob()
.setName('TESTING.xlsx')]
});
DriveApp.getFileById(copySS.getId()).setTrashed(true);
}

To share Drive file to specific people, try to add setSharing(accessType, permissionType) method given in Class File.
As mentioned in Working with enums,
the Drive service uses the enums Access and Permission to determine which users have access to a file or folder.
So to access file or folder in DriveApp, you should add the following enumerated types to determine users who can access a file or folder, besides any individual users who have been explicitly given access
Access
Permission
It will really be helpful to try going through the given documentations.

I took the easy way out and made a new spreadsheet and I am importing to that spreadsheet using a script, so now the new document just has data on it and is working perfectly now.

Related

Converting a specific sheet in a workbook to a PDF

I am trying to convert a specific sheet in a workbook to PDF. I got help from some kind people here. However, the code worked once and gave me the desired result but then it stopped working and stated giving me a "Exception: Request failed for https://docs.google.com returned code 500." error.
I have a workbook and in that workbook I have a sheet call 'CallPDF' which I want to convert to a PDF. The script that I used is as follows;
const ss = SpreadsheetApp.getActiveSpreadsheet();
const cfrm = ss.getSheetByName('CallPDF');
function saveCRecord() {
var shan = DriveApp.getFolderById("1RzP4dBMU_ZJRvT0WWF1JLvNRztgzSyRT");
if(cfrm.getRange("H8").getValue() == "Shan Jose") {
const url = `https://docs.google.com/spreadsheets/d/${ss.getId()}/export format=pdf&gid=${ss.getSheetByName('CallPDF').getSheetId()}`;
const blob = UrlFetchApp.fetch(url, { headers: { authorization: "Bearer " + ScriptApp.getOAuthToken() } }).getBlob();
shan.createFile(blob.setName(fileName));
};
}
This code worked for me once and then it started giving me the 'Return Code 500' error. As per the code, it will first check if the values in a cell matches the criteria and if it does then convert the CallPDF sheet to a PDF file, rename it and then save it in a specific folder in Google Drive.
Hoping that someone can help me refine this code and get it working for me.
I have been referencing many codes and sites but it is still giving me the error. I am not a coder or a programmer so my knowledge is very limited which is why I am reaching out for help here from the experts.
Some links that I referenced are;
https://spreadsheet.dev/comprehensive-guide-export-google-sheets-to-pdf-excel-csv-apps-script
How to download single sheet as PDF to my local device directly (not export to Google Drive)?

"setOwner" not a function error - App Script

new to Google Scripts and I've looked through other posts on Stack Overflow as well but couldn't find a good answer.
I'm using data collected in Google Sheets to search for a file in Google Drive and transfer ownership of the file. I have google form that my users fill out, once submitted using an add-on I create a file based on the data that was submitted on the form. Now with the script, I'm trying to go gather certain information from sheets such as name, email, and company name -
Sample data image here.
What I have thus far:
function myFunction() {
//Get google sheets
var spreadsheetId = '1WvIIoYdmuIB5BQ3KgSYOOIiEn-K_GTzCkb7rITzRFck';
//get certain values from sheets
var rangeName = 'MDP Form!C25:E';
var values = Sheets.Spreadsheets.Values.get(spreadsheetId, rangeName).values;
if (!values) {
Logger.log('No data found.');
} else {
Logger.log('Name, Email, Customer:');
for (var row = 0; row < values.length; row++) {
// Print columns C and E, which correspond to indices 0 and 4.
Logger.log('Name: %s, Email: %s, Company: %s', values[row][0], values[row][1], values[row][2]);
//Utilities.sleep(90000);
//Searching through google drive
var name = (values[row][0]);
var email = (values[row][1]);
Logger.log(email);
var company = (values[row][2]);
var fileName = ('Mutual Delivery Plan ' + company + ' - ' + name);
Logger.log(fileName);
//add a 1 minute delay
//Utilities.sleep(90000);
//search for target folder
var folder = DriveApp.getFolderById('1whvRupu9hWdyl2CqSF-KvdVj8VE6iiQu');
//search for file by name within folder
var mdpFile = folder.searchFiles(fileName);
//transfer ownership
mdpFile.setOwner(email);
}
}
}
Problem:
The script works for the most part except for the last line "setOwner" is not a function. I've tried creating a separate function for this, used some other suggestions on other posts but still cannot get this to work. If anyone has ideas around what might I be missing here or suggestions that would be super helpful. Thanks!
I believe your goal as follows.
You want to transfer the owner of the file when the file with fileName is found in folder.
For this, how about this answer?
Modification points:
Although you say The script works for the most part except for the last line "setOwner" is not a function., if your script in your question is the current script, how about the following modification?
In your script, fileName is 'Mutual Delivery Plan ' + company + ' - ' + name, and fileName is used with var mdpFile = folder.searchFiles(fileName);. In this case, an error occurs. Because params of searchFiles(params) is required to be the query string.
I think that in your case, it's "title='" + fileName + "'".
Also searchFiles(fileName) returns FileIterator. This has already mentioned by the existing answer. Because at Google Drive, the same filenames can be existing in the same folder and each files are managed by the unique ID. So here, it is required to be modified as follows.
I think that in your case, the following flow is useful.
Confirm whether the file is existing using hasNext().
When the file is existing and the owner is you, the owner of the file is changed to email.
When above points are reflected to your script, please modify as follows.
Modified script:
From:
var mdpFile = folder.searchFiles(fileName);
//transfer ownership
mdpFile.setOwner(email);
To:
var mdpFile = folder.searchFiles("title='" + fileName + "'");
while (mdpFile.hasNext()) {
var file = mdpFile.next();
if (file.getOwner().getEmail() == Session.getActiveUser().getEmail()) {
file.setOwner(email);
}
}
If you don't need to check whether the owner is you, please remove if (file.getOwner().getEmail() == Session.getActiveUser().getEmail()) {.
Note:
In this case, when the file with the filename of fileName is not existing in folder, the script in the if statement is not run. Please be careful this.
Also, when there are several files with the same filename in folder, the owner of those is changed to email.
References:
searchFiles(params)
FileIterator
hasNext()
next()
getActiveUser()
Folder.searchFiles() returns a fileIterator not a file. If it's the only file with that name then you can usually getaway with mdpFile.next();
File Iterator

Attaching Google doc link read from Google spreadsheet to automatic email in script

The following code isn't working, giving the following error:
TypeError: Cannot find function getFileByID in object Drive.
I'm trying to first test by directly providing ID in the script:
var atta = DriveApp.getFileByID('1XD...c'); //ID is Folder and Google Doc ID I want to attach
MailApp.sendEmail(emailto, subject, message, {
cc: emailcc,
attachments:[atta]
});
Ultimately, I want to read in the link from a Google Spreadsheet:
var range = active_actions.getRange(i+1,16) //active_actions is the spreadsheet and i+1,16 is the cell with the link
var link = range.getFormula();
var atta = DriveApp.getFileByID(link);
MailApp.sendEmail(emailto, subject, message, {
cc: emailcc,
attachments:[atta]
});
This isn't too difficult. Google Docs/Spreadsheets/etc. CANNOT be placed as an attachment in an E-mail. This is because it isn't actually a 'physical document'. It only exists on the cloud. Instead, put the URL in the email, and it will give the receiver a little box at the bottom with the Doc looking like an attachment.
It's not perfect, but it is good enough. For more details, you can see this issue request or Google's App Script Issue page:
https://code.google.com/p/google-apps-script-issues/issues/detail?id=585&q=attachment%20types&sort=-stars&colspec=Stars%20Opened%20ID%20Type%20Status%20Summary%20Component%20Owner
EDIT (To explain data fetching in SS):
To get data out of a range object, (text, number, etc.), you should use this format.
var range = getRange();
var rangeData;
var cellValue;
while (range.hasNext()) {
rangeData = range.next();
cellValue = rangeData.getValue();
}
If you an accumulator variable, you can get every bit of data in one list/string/etc.
Now that you have your data, you can E-mail it, or do anything else with it.

Google app scripts: email a spreadsheet as excel

How do you make an app script which attaches a spreadsheet as an excel file and emails it to a certain email address?
There are some older posts on Stackoverflow on how to do this however they seem to be outdated now and do not seem to work.
Thank you.
It looks like #Christiaan Westerbeek's answer is spot on but its been a year now since his post and I think there needs to be a bit of a modification in the script he has given above.
var url = file.exportLinks[MimeType.MICROSOFT_EXCEL];
There is something wrong with this line of code, maybe that exportLinks has now depreciated. When I executed his code it gave an error to the following effect:
TypeError: Cannot read property "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" from undefined.
The workaround is as follows:
The URL in the above line of code is basically the "download as xlsx" URL that can be used to directly download the spreadsheet as an xlsx file that you get from File> Download as > Microsoft Excel (.xlsx)
This is the format:
https://docs.google.com/spreadsheets/d/<<<ID>>>/export?format=xlsx&id=<<<ID>>>
where <<>> should be replaced by the ID of your file.
Check here to easily understand how to extract the ID from the URL of your google sheet.
Here's an up-to-date and working version. One prerequisite for this Google Apps script to work is that the Drive API v2 Advanced Google Service must be enabled. Enable it in your Google Apps script via Resources -> Advanced Google Services... -> Drive API v2 -> on. Then, that window will tell you that you must also enabled this service in the Google Developers Console. Follow the link and enable the service there too! When you're done, just use this script.
/**
* Thanks to a few answers that helped me build this script
* Explaining the Advanced Drive Service must be enabled: http://stackoverflow.com/a/27281729/1385429
* Explaining how to convert to a blob: http://ctrlq.org/code/20009-convert-google-documents
* Explaining how to convert to zip and to send the email: http://ctrlq.org/code/19869-email-google-spreadsheets-pdf
* New way to set the url to download from by #tera
*/
function emailAsExcel(config) {
if (!config || !config.to || !config.subject || !config.body) {
throw new Error('Configure "to", "subject" and "body" in an object as the first parameter');
}
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var spreadsheetId = spreadsheet.getId()
var file = Drive.Files.get(spreadsheetId);
var url = 'https://docs.google.com/spreadsheets/d/'+spreadsheetId+'/export?format=xlsx';
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
var fileName = (config.fileName || spreadsheet.getName()) + '.xlsx';
var blobs = [response.getBlob().setName(fileName)];
if (config.zip) {
blobs = [Utilities.zip(blobs).setName(fileName + '.zip')];
}
GmailApp.sendEmail(
config.to,
config.subject,
config.body,
{
attachments: blobs
}
);
}
Update: I updated the way to set the url to download from. Doing it through the file.exportLinks collection is not working anymore. Thanks to #tera for pointing that out in his answer.

Overwrite an Image File with Google Apps Script

Can I overwrite an image file with Google Apps Script? I've tried:
file.setContent(newBlobImage);
file.replace(newBlobImage);
Neither of those work. .setContent() will delete whatever data was in the file, and it looks like maybe it just writes the variable name as text, or something like that. I'm assuming that both .setContent() and .replace() are meant for text documents, and maybe that's why they don't work.
If it were a text file, or a spreadsheet, I might be able to clear it, then append new content.
I can trash the file, then create a new one, but I'd rather not if there is some other way.
If I write a file with the same name, it won't overwrite the existing file, it creates a another file with the same name.
The only way I've been able to trash the file is with DocsList and the only success I've had with creating an image file is with DriveApp. So I have to trash the file with DocsList, then create another file with DriveApp.
Well, I've figured out how to delete the file without sending it to the trash, so I won't need to clean out the trash later. The Google Drive SDK inside of Apps Script has a remove method that didn't send the file to trash, it's just gone.
var myFolder = DriveApp.getFolderById('3Bg2dKau456ySkhNBWB98W5sSTM');
thisFile = myFolder.getFilesByName(myFileName);
while (thisFile.hasNext()) {
var eachFile = thisFile.next();
var idToDLET = eachFile.getId();
Logger.log('idToDLET: ' + idToDLET);
var rtrnFromDLET = Drive.Files.remove(idToDLET);
};
So, I'm combining the DriveApp service and the DriveAPI to delete the file without sending it to the trash. The DriveAPI .remove needs the file ID, but I don't have the file ID, so the file gets looked up by name, then the file ID is retrieved, then the ID is used to delete the file. So, if I can't find a way to overwrite the file, I can at least delete the old file without it going to the trash.
I just noticed that the DriveAPI service has a Patch and an Update option.
.patch(resource, fileId, optionalArgs)
Google Documentation Patch Updates file metadata.
The resource arg is probably the metadata. The fileId is self explanatory. I'm guessing that the optionalArgs are parameters that follow the HTTP Request Patch semantics? I don't know.
It looks like both Patch and Update will update data. Update is a PUT request that will
clears previously set data if you don't supply optional parameters.
According to the documentation. So it's safer to use a Patch request because any parameters that are missing are simply ignored. I haven't tried it yet, but maybe this is the answer.
I'm getting an error with Patch, so I'll try Update:
.update(resource, fileId, mediaData)
That has a arg for mediaData in the form of a blob. And I think that is what I need. But I'm not sure what the resource parameter needs. So I'm stuck there.
An image file can be overwritten with Google Apps Script and the DriveAPI using the update() method:
.update(File resource, String fileId, Blob mediaData)
Where file resource is:
var myFileName = 'fileName' + '.jpg';
var file = {
title: myFileName,
mimeType: 'image/jpeg'
};
I'm getting the file ID with the DriveApp service, and the Blob is what was uploaded by the user.
In order to use DriveAPI, you need to add it through the Resources, Advanced Google Services menu. Set the Drive API to ON.
var allFilesByName,file,myFolder,myVar,theFileID,thisFile;
//Define var names without assigning a value
file = {
title: myFileName,
mimeType: 'image/jpeg'
};
myFolder = DriveApp.getFolderById('Folder ID');
allFilesByName = myFolder.getFilesByName(myFileName);
while (allFilesByName.hasNext()) {
thisFile = allFilesByName.next();
theFileID = thisFile.getId();
//Logger.log('theFileID: ' + theFileID);
myVar = Drive.Files.update(file, theFileID, uploadedBlob);
};
Thank you for this track !
This allowed me to find a solution to my problem : move a bound form after copying and moved his spreadsheet.
The Drive app advanced service must be activated in the "Resource Script Editor" to run this script.
function spreadsheetCopy() {
// Below is the file to be copied with a bound form.
var fileToCopy = DriveApp.getFileById("file_key"); // key is fileId
var saveFolder = DriveApp.getFolderById("folder_key"); // key is folderId
var currentFolder = "";
( fileToCopy.getParents().next() ) ? currentFolder = fileToCopy.getParents().next() : currentFolder = DriveApp.getRootFolder();
Logger.log(currentFolder)
var copyFile = fileToCopy.makeCopy(saveFolder),
copyName = copyFile.getName();
Utilities.sleep(30000);
moveFormCopy(currentFolder, saveFolder, copyName);
}
function moveFormCopy(currentFolder, saveFolder, copyName) {
var formsInFolder = currentFolder.getFilesByType(MimeType.GOOGLE_FORMS);
var form, copyForm, copyFormMimeType, copyFormName, copyFormId;
while ( formsInFolder.hasNext() ) {
form = formsInFolder.next();
if ( copyName === form.getName() ) {
copyForm = form;
copyFormMimeType = copyForm.getMimeType();
copyFormName = copyForm.getName();
copyFormId = copyForm.getId();
break;
}
};
var resource = {title: copyName, mimeType: copyFormMimeType};
Drive.Files.patch(resource, copyFormId, {addParents: saveFolder.getId(), removeParents: currentFolder.getId()})
}