我正在尝试将Google电子表格另存为pdf并在每次编辑电子表格中的特定单元格时将其发送给自己。我有一个脚本,它将电子表格保存为pdf并通过电子邮件发送它并且它有效,我还有一个onEdit(e)脚本,它完全符合我的要求。但是,当我把它们放在一起时它不起作用。这是脚本:
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函数完成“export as pdf”任务太多了吗?因为我在另一个脚本中执行完全相同的操作,我每天都会触发它并且工作正常。
答案 0 :(得分:1)
您应该使用可安装的onEdit触发器,因为无法使用简单触发器发送电子邮件。
ScriptApp.newTrigger("onEdit")
.forSpreadsheet(SpreadsheetApp.getActive())
.onEdit()
.create();
答案 1 :(得分:0)
//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();
我认为激活是一种不用于电子表格的工作表方法。您可以从SpreadsheetApp打开电子表格。
//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'};
我认为您需要在这两个语句之间使用DriveApp创建pdf文件。适用于DriveApp.createFile