this script sends a pdf copy to my email when I type Send in cell L6 , this code send the whole sheet and I need to send as only A1:J22 , any Ideas ?
function onEdit2(e) {
var sheet = SpreadsheetApp.getActiveSheet();
var r = sheet.getRange('L6').getValue();
if (r == "Send") {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var ssID = ss.getId();
var sheetgId = ss.getActiveSheet().getSheetId();
var sheetName = ss.getName();
var token = ScriptApp.getOAuthToken();
var email = "EMAIL HERE";
var subject = "Daily report ";
var body = "Please find the attached Daily report";
var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?"
+ "format=xlsx" + "&gid="+sheetgId+ "&portrait=true" +
"&exportFormat=pdf";
var result = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
var contents = result.getContent();
MailApp.sendEmail(email,subject ,body, {
attachments: [{
fileName: sheetName + ".pdf",
content: contents,
mimeType: "application//pdf"
}]
})
}
}
You want to retrieve the cells of A1:J22 and want to create them to PDF data.
You want to achieve this using Google Apps Script.
If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
Modification points:
In this modification, create a temporal sheet and copy the values of the cells of A1:J22 to it. Then, the temporal sheet is converted to PDF file. And, the temporal sheet is deleted.
Modified script:
When your script is modified, please modify as follows.
function onEdit2(e) {
var sheet = SpreadsheetApp.getActiveSheet();
var r = sheet.getRange('L6').getValue();
if (r == "Send") {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var ssID = ss.getId();
var sheet = ss.getActiveSheet(); // Added
// var sheetgId = ss.getActiveSheet().getSheetId(); // removed
var sheetName = ss.getName();
var token = ScriptApp.getOAuthToken();
var email = "EMAIL HERE";
var subject = "Daily report ";
var body = "Please find the attached Daily report";
var tempSheet = ss.insertSheet("tempSheet"); // Added
sheet.getRange("A1:J22").copyTo(tempSheet.getRange(1, 1)); // Added
SpreadsheetApp.flush(); // Added
var sheetgId = tempSheet.getSheetId(); // Added
var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?" + "format=xlsx" + "&gid="+sheetgId+ "&portrait=true" + "&exportFormat=pdf";
var result = UrlFetchApp.fetch(url, {headers: {'Authorization': 'Bearer ' + token}});
var contents = result.getContent();
MailApp.sendEmail(email,subject ,body, {attachments: [{fileName: sheetName + ".pdf", content: contents, mimeType: "application//pdf"}]});
ss.deleteSheet(tempSheet); // Added
}
}
References:
insertSheet(sheetName)
copyTo(destination)
deleteSheet(sheet)
If I misunderstood your question and this was not the direction you want, I apologize.
Related
I have a script to send the active sheet of a workbook sheet in excel to a mailing list
function SendaMailOK(){
var DateName1 = SpreadsheetApp.getActiveSheet( ).getRange("B4").getValue();
var newdate = new Date(SpreadsheetApp.getActiveSheet( ).getRange("B4").getValue());
var d = Utilities.formatDate(newdate, Session.getScriptTimeZone(), "dd-MM-yyyy");
var f = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Adresses Mail');
//Send active sheet as email attachment
var ss = SpreadsheetApp.getActiveSpreadsheet()
var ssID = ss.getId();
var sheetgId = ss.getActiveSheet().getSheetId();
var sheetName = ss.getSheetName();
var token = ScriptApp.getOAuthToken();
var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?" + "format=xlsx" + "&gid="+sheetgId+ "&portrait=false" + "&exportFormat=xlsx";
var result = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
var contents = result.getContent();
var subject = "Rapport du " + d;
var body = "Bonjour, \n\nCi-joint le rapport, \n \nCdlt";
var n=f.getLastRow();
for (var i = 1; i < n+1 ; i++ ) {
var emailAddress = f.getRange(i,1).getValue();
MailApp.sendEmail(emailAddress,subject ,body, {attachments:[{fileName:sheetName+".xlsx", content:contents, mimeType:"application//xlsx"}]});
}
};
After modifying my file, I need to send 2 sheets of the workbook as attachments and no longer the active sheet.
Problem, I can't adapt the script.
Thanks for your help.
Sending multiple files
I played around with your code a little and found a way to do it taking from some of the work that Tanaike has done in this area. If you don't know where to look for stuff like this then always check out Tanaikes work because I've always found it to be well done.
function SendaMailOK() {
const ss = SpreadsheetApp.getActive();
let esh = ss.getSheetByName('Sheet3');
let ssID = ss.getId();
let token = ScriptApp.getOAuthToken();
let emails = esh.getRange(1, 1, esh.getLastRow()).getValues().flat().join(',');
const names = ['Sheet0', 'Sheet1'];
const shts = ss.getSheets().filter(sh => ~names.indexOf(sh.getName()));
let files = [];
shts.forEach((sh, i) => {
let d = Utilities.formatDate(new Date(sh.getRange("B4").getValue()), Session.getScriptTimeZone(), "dd-MM-yyyy");
let sheetgId = sh.getSheetId();
let url = "https://docs.google.com/spreadsheets/d/" + ssID + "/export?" + "format=xlsx" + "&gid=" + sheetgId + "&portrait=false" + "&exportFormat=xlsx";
let contents = UrlFetchApp.fetch(url, { headers: { 'Authorization': 'Bearer ' + token } }).getBlob().setName(`${sh.getName()}.xlsx`);
files.push(contents);
});
var subject = `Files: ${names.join(', ')}`;
var body = "Hello, here are your files";
MailApp.sendEmail(emails, subject, body, { attachments: files });
}
I am trying to automate by a script the sending of a Sheet (active or not) of a workbook and only one sheet and not the whole workbook to a list of email addresses. Furthermore, I would like the Sheet to be converted to excel format when it is attached to the email.
Thank you for your answers
Try this:
function emailSpreadsheetAsPDF() {
const sheetToPrint = 'SPREADSHEET_NAME'; // name of the sheet to print
const ss = SpreadsheetApp.getSheetByName('SHEET_NAME'); // the sheets to use
const email = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('SHEET_NAME').getRange('RANGE').getValue().toString(); // grab the email address from the specified cell
const subject = `SUBJECT - ${ss.getName()}`; // the subject of the email
const body = "BODY"; // body of the email
const shID = ss.getSheetByName(sheetToPrint).getSheetId(); // the ID of the sheet
const url = 'https://docs.google.com/spreadsheets/d/SS_ID/export?'.replace('SS_ID', ss.getId()); // url of the spreadsheet
const exportOptions =
'exportFormat=pdf&format=xlsx' + // export as pdf / csv / xls / xlsx
'&gid='+shID; // the sheet's Id
var params = {method:"GET",headers:{"authorization":"Bearer "+ ScriptApp.getOAuthToken()}};
// generate the file
var response = UrlFetchApp.fetch(url+exportOptions, params).getBlob();
// send the email to the specified address with the specified body text and attached file
GmailApp.sendEmail(email, subject, body, {
htmlBody: body,
attachments: [{
fileName: `EKOL Hungary - ${ss.getName()}` + ".xlsx",
content: response.getBytes(),
mimeType: "application/xlsx"
}]
});
}
Just substitute the SPREADSHEET_NAME, SHEET_NAME, RANGE, and BODY to what is true for your spreadsheet.
You can add a Trigger under the Triggers menu point (left side of the Script Editor) to automatically run the script whenever you want it to run.
Thanks but I failed to use it
But by combining several scripts, I found one that works:
function onSubmit(e){
Logger.log('submit ran');
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
//Send active sheet as email attachment
var ss = SpreadsheetApp.getActiveSpreadsheet()
var ssID = ss.getId();
var sheetgId = ss.getActiveSheet().getSheetId();
var sheetName = ss.getName();
var token = ScriptApp.getOAuthToken();
var email = "xxx#xx";
var subject = "xxxxx";
var body = "xxxxx";
var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?" + "format=xlsx" + "&gid="+sheetgId+ "&portrait=false" + "&exportFormat=xlsx";
var result = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
var contents = result.getContent();
MailApp.sendEmail(email,subject ,body, {attachments:[{fileName:sheetName+".xlsx", content:contents, mimeType:"application//xlsx"}]});
};
Now what I would like is to be able to send the sheet to email addresses located on another sheet.
Also in "subject", I would like to combine "xxxx" + a date in a cell of the active sheet: "xxxx dd / mm / yyyy"
I haven't figured out how to do it yet !!!
my google sheet will email a PDF copy of the sheet to a list of 4 emails ( in cells L5:L8 )
but it seems that the email in cell L8 never picked , logger shows it in the array ! .
see my code and help figuring the problem !? I'm suspecting something wrong in my FOREACH loop .
function onEdit2(e) {
var sheet = SpreadsheetApp.getActiveSheet();
var r = sheet.getRange('L11').getValue();
if (r == "Send") {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var ssID = ss.getId();
var sheet = ss.getActiveSheet();
var sheetName = ss.getName();
var key = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
var token = ScriptApp.getOAuthToken();
var setcolor= SpreadsheetApp.getActiveSheet().setTabColor("#0000A0");
var emails= sheet.getRange("L5:L8").getValues();
var subject = "Daily report ";
var body = "Please find the attached" +" "+ key ;
var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?"
+ "format=xlsx" + "&gid="+sheetgId+ "&portrait=true" +
"&exportFormat=pdf";
var tempSheet = ss.insertSheet("tempSheet"); // Added
sheet.getRange("A1:J27").copyTo(tempSheet.getRange(1, 1)); // Added
SpreadsheetApp.flush(); // Added
var sheetgId = tempSheet.getSheetId(); // Added
var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?" + "format=xlsx" + "&gid="+sheetgId+ "&portrait=true" + "&exportFormat=pdf";
var result = UrlFetchApp.fetch(url, {headers: {'Authorization': 'Bearer ' + token}});
var contents = result.getContent();
emails.forEach(function(email){
MailApp.sendEmail(email.toString(),sheetName ,body, {attachments: [{fileName: sheetName + ".pdf", content: contents, mimeType: "application//pdf"}]});
ss.deleteSheet(tempSheet); // Added
})
}
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
for ( var i = 0 ; i<sheets.length ; i++) {
var sheet1 = sheets[i];
sheet1.getRangeList(['L3','L11']).clearContent();
}
}
I'm trying to make this script to work on google sheets app so it sends a pdf copy to my email when I type Send in cell L6
the code work perfect on computer but not on ipads , anyway to do this from app ?
function onEdit2(e) {
var sheet = SpreadsheetApp.getActiveSheet();
var r = sheet.getRange('L6').getValue();
if (r == "Send") {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var ssID = ss.getId();
var sheetgId = ss.getActiveSheet().getSheetId();
var sheetName = ss.getName();
var token = ScriptApp.getOAuthToken();
var email = "EMAIL HERE";
var subject = "Daily report ";
var body = "Please find the attached Daily report";
var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?"
+ "format=xlsx" + "&gid="+sheetgId+ "&portrait=true" +
"&exportFormat=pdf";
var result = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
var contents = result.getContent();
MailApp.sendEmail(email,subject ,body, {
attachments: [{
fileName: sheetName + ".pdf",
content: contents,
mimeType: "application//pdf"
}]
})
}
}
The way it worked for me by " installed Trigger "
from the script editor : Edit - current project Triggers
I added new trigger that will run the code below based on " On edit " and voila it worked , from sheets app if I typed " Send " in Cell L6 it will send a PDF copy of the active sheet to the email listed in the code.
function onEdit2(e) {
var sheet = SpreadsheetApp.getActiveSheet();
var r = sheet.getRange('L6').getValue();
if (r == "Send") {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var ssID = ss.getId();
var sheetgId = ss.getActiveSheet().getSheetId();
var sheetName = ss.getName();
var token = ScriptApp.getOAuthToken();
var email = "EMAIL HERE";
var subject = "Daily report ";
var body = "Please find the attached Daily report";
var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?"
+ "format=xlsx" + "&gid="+sheetgId+ "&portrait=true" +
"&exportFormat=pdf";
var result = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
var contents = result.getContent();
MailApp.sendEmail(email,subject ,body, {
attachments: [{
fileName: sheetName + ".pdf",
content: contents,
mimeType: "application//pdf"
}]
})
}
}
Create a Google Script in the very same Spreadsheet or in another one (Tools / Script editor), add the script you already have, grant the authorizations required, and trigger it with a simple form (Tools / Create a form) (trigger → Edit / Current project's triggers). The long URL to view the form can be easily opened by means of a URL shortener or something by the sort. Forms work in cell phones too and without need to sign in to your account. With this method you can even add a useless conditional password to run the script.
function createPDF(e) {
var input = e.values[1];
if (input == 'my_password'){
// your scripts to create and send the PDF goes here
}
}
It's a simplistic solution, but it works.
In the new Google Spreadsheet I have a large script that clears the contents from many cells throughout 8 different sheets.
The formulas that total up the sheet is the only section that is protected, but I keep getting the error on the .clearContent(); method when the script isn't touching any of the protected cells.
Any thoughts? This is the identical script used (working perfect) on the old spreadsheets.
function masterCloseWeek() {
var hideLiqOrder = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('LIQUOR ORDER');
hideLiqOrder.hideSheet();
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var costReport = spreadsheet.getSheetByName('COST REPORT').activate();//Moves sheet to position 1
spreadsheet.moveActiveSheet(1);
var invoiceLog = spreadsheet.getSheetByName('INVOICE LOG').activate();//Moves sheet to position 2
spreadsheet.moveActiveSheet(2);
var dailyInventory = spreadsheet.getSheetByName('DAILY INVENTORY').activate();//Moves sheet to position 3
spreadsheet.moveActiveSheet(3);
SpreadsheetApp.flush();
var spreadsheetId = 'xxxxxxxxxxxx'; //ID
var file = Drive.Files.get(spreadsheetId);
var url = file.exportLinks['application/pdf'];
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
//var pdf = response.getBlob();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getName();
var pdf = response.getBlob().setName(ss.getName() + '.pdf');
var CopyDate = Utilities.formatDate(new Date(), "GMT-3", "MM/dd/yyyy HH:mm"); // Funtion Date + Format
DocsList.createFile(pdf);
MailApp.sendEmail({
to:"myEmail#test.com",
subject: "Blank (v2.0) Weekly File Attached" + "_" + "Sent on " + CopyDate,
body:"(This is an automated email.).....Attached is a copy of the weekly file sent on" + " "+CopyDate,
attachments: [pdf]
})
var hideLiqOrder = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('LIQUOR ORDER');
hideLiqOrder.showSheet();
var liquorInventory = SpreadsheetApp.getActive().getSheetByName('LIQUOR INVENTORY');
liquorInventory.getRange('J6:J588').copyTo(liquorInventory.getRange('M6:M588'),{contentsOnly:true});
var foodInventory = SpreadsheetApp.getActive().getSheetByName('FOOD INVENTORY');
foodInventory.getRange('G5:G622').copyTo(foodInventory.getRange('I5:I622'),{contentsOnly:true});
//Finished closing week
//Starting a new week
var activeSheet = SpreadsheetApp.getActiveSpreadsheet();
var costReport = activeSheet.getSheetByName('COST REPORT');
var FraminghamSnapShot = activeSheet.getSheetByName('FraminghamSnapShot');
costReport.getRange('E12:E16').copyTo(FraminghamSnapShot.getRange('B23:B27'),{contentsOnly:true});
This is the first error, when it tries to clear invoiceLog.getRange('A3:L52').clearContent();
var invoiceLog = SpreadsheetApp.getActive().getSheetByName('INVOICE LOG');
invoiceLog.getRange('A3:L52').clearContent();
var dailyInventory = SpreadsheetApp.getActive().getSheetByName('DAILY INVENTORY');
dailyInventory.getRange('C5:C9').clearContent();
dailyInventory.getRange('D6:I9').clearContent();
dailyInventory.getRange('C13:C17').clearContent();
dailyInventory.getRange('D14:I17').clearContent();
dailyInventory.getRange('C21:C25').clearContent();
dailyInventory.getRange('D22:I25').clearContent();
dailyInventory.getRange('C29:C33').clearContent();
dailyInventory.getRange('D30:I33').clearContent();
dailyInventory.getRange('C37:C41').clearContent();
dailyInventory.getRange('D38:I41').clearContent();
dailyInventory.getRange('C45:C49').clearContent();
dailyInventory.getRange('D46:I49').clearContent();
dailyInventory.getRange('C55:C59').clearContent();
dailyInventory.getRange('D56:I59').clearContent();
dailyInventory.getRange('C63:C67').clearContent();
dailyInventory.getRange('D64:I67').clearContent();
dailyInventory.getRange('C71:C75').clearContent();
dailyInventory.getRange('D72:I75').clearContent();
dailyInventory.getRange('C79:C83').clearContent();
dailyInventory.getRange('D80:I83').clearContent();
dailyInventory.getRange('C87:C91').clearContent();
dailyInventory.getRange('D88:I91').clearContent();
dailyInventory.getRange('C95:C99').clearContent();
dailyInventory.getRange('D96:I99').clearContent();
dailyInventory.getRange('C105:C109').clearContent();
dailyInventory.getRange('D106:I109').clearContent();
dailyInventory.getRange('C113:C117').clearContent();
dailyInventory.getRange('D114:I117').clearContent();
dailyInventory.getRange('C121:C125').clearContent();
dailyInventory.getRange('D122:I125').clearContent();
dailyInventory.getRange('C129:C133').clearContent();
dailyInventory.getRange('D130:I133').clearContent();
dailyInventory.getRange('C137:C141').clearContent();
dailyInventory.getRange('D138:I141').clearContent();
dailyInventory.getRange('C145:C149').clearContent();
dailyInventory.getRange('D146:I149').clearContent();
var foodInventory = SpreadsheetApp.getActive().getSheetByName('FOOD INVENTORY');
foodInventory.getRange('D5:F622').clearContent();
var liquorInventory = SpreadsheetApp.getActive().getSheetByName('LIQUOR INVENTORY');
liquorInventory.getRange('E6:I371').clearContent(); //Vodka thru Wines
liquorInventory.getRange('G375:I433').clearContent(); //Draft Beer
liquorInventory.getRange('G437:I535').clearContent(); //Bottle Beer
liquorInventory.getRange('E539:I588').clearContent(); //Non Alcoholic
var dailySalesSheet = SpreadsheetApp.getActive().getSheetByName('DAILY SALES SHEET');
dailySalesSheet.getRange('B4:H11').clearContent(); //Sales Categories
var costReport = SpreadsheetApp.getActive().getSheetByName('COST REPORT');
costReport.getRange('F12:F16').clearContent(); //Theoreticals
costReport.getRange('D20:D20').clearContent(); //Week Ending Date
var safeAudit = SpreadsheetApp.getActive().getSheetByName('SAFE AUDIT');
safeAudit.getRange('C3:P11').clearContent();
safeAudit.getRange('C14:P18').clearContent();
safeAudit.getRange('C22:P22').clearContent();
var destination = SpreadsheetApp.getActiveSpreadsheet();
Browser.msgBox('Closed Successfully','Your week has been successfully closed\\n and emailed.', Browser.Buttons.OK);
var name = Browser.inputBox('Enter Week Ending Date ONLY', 'Example: 11-5-14 \\n\\n', Browser.Buttons.OK);
destination.rename("BlankWE" + name);
costReport.getRange('D20').setValue(name);
}
Is there a better more efficient way to clear cells? Would that help solve the issue?
Sean.
Well, I don't find anything wrong in your invoiceLog.getRange('A3:L52').clearContent();, it works perfectly for me.