使用onEdit()将工作表另存为pdf [英] Save a sheet as pdf with onEdit()
问题描述
我正在尝试将Google电子表格另存为pdf,并在每次编辑电子表格中的特定单元格时将其邮寄给自己.我有将电子表格另存为pdf并通过电子邮件发送的脚本,它可以工作,并且我还有一个onEdit(e)脚本,可以完全满足我的需求.但是,当我将它们放在一起时,它不起作用.这是脚本:
i'm trying to save a google spreadsheet as pdf and mail it to myself everytime, when a specific cell in the spreadsheet is edited. I have the script which saves the spreadsheet as pdf and emails it and it works and I also have an onEdit(e) script which does exactly what I want. But when I put them together it doesn't work. Here's the script:
function onEdit(e) {
var sheet1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("booking");
var index = sheet1.getRange('O5').getValue();
if(index == '#N/A') return;
var email = "myemail@gmail.com";
var subject = "Subject";
var sheet3 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Invoice_ENG");
var pdfname = ("PDF.pdf");
var message = ("Hello!");
//Since I can't export only one sheet, I create a new spreadsheet, copy the sheet
//into the new spreadsheet and save the new spreadsheet as pdf
var newSpreadsheet = SpreadsheetApp.create("Spreadsheet to export");
sheet3.copyTo(newSpreadsheet);
//I erase the default Sheet1 from the new Spreadsheet
var ss = newSpreadsheet.getSheetByName('Sheet1');
ss.activate();
newSpreadsheet.deleteActiveSheet();
//Create pdf --- THIS IS WHERE THE SCRIPT SOMEHOW STOPS!
var pdf = DriveApp.getFileById(newSpreadsheet.getId()).getAs('application/pdf').getBytes();
var attach = {fileName:pdfname,content:pdf, mimeType:'application/pdf'};
//Send mail
GmailApp.sendEmail(email, subject, message, {attachments:[attach]});
//Erase the newly created spreadsheet
DriveApp.getFileById(newSpreadsheet.getId()).setTrashed(true);
}
使用onEdit函数无法完成导出为pdf"任务吗?因为我正在每天触发的另一个脚本中执行完全相同的操作,所以效果很好.
Is the "export as pdf" task too much to be done with an onEdit function? Because I'm doing the exact same thing in another script which I trigger daily and it works fine.
推荐答案
您应该使用可安装的onEdit触发器,因为使用简单的触发器无法发送电子邮件.
You should use an installable onEdit trigger as sending email cannot be done with simple trigger.
ScriptApp.newTrigger("onEdit")
.forSpreadsheet(SpreadsheetApp.getActive())
.onEdit()
.create();
这篇关于使用onEdit()将工作表另存为pdf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!