菜单驱动的按需操作
在 Google 表格用户界面中,菜单项是一种将其设置为按需运行的自然方式。1 Google 的 @ 是学习如何自己执行此操作的好资源987654321@。
在该教程中,以下代码可将“发送报告”菜单项添加到您的电子表格,选中时将调用 sendReport_() 函数:
/**
* A special function that runs when the spreadsheet is open, used to add a
* custom menu to the spreadsheet.
*/
function onOpen() {
var spreadsheet = SpreadsheetApp.getActive();
var menuItems = [
{name: 'Send Report', functionName: 'sendReport_'}
];
spreadsheet.addMenu('Custom', menuItems);
}
sendReport_()函数
假设我们有一个getPdfBlob() 函数,它将返回一个适合附加到电子邮件的blob。有了这些,sendReport_() 需要做的事情就在这里:
// From https://stackoverflow.com/a/37149036/1677912
function sendReport_() {
// Configuration parameters; customize as you wish
var sheetName = "Report";
var subject = "Email subject line";
var recipients = "user1@example.com, user2@example.com";
var htmlMessage = "Greetings,<br/><br/>"
+ "Please find today's report attached as a PDF.<br/><br/>"
+ "Cheers,<br/><br/>Paranoia";
// Get the IDs of the spreadsheet & sheet-of-interest
var ss = SpreadsheetApp.getActive();
var sheetId = ss.getSheetByName(sheetName).getSheetId();
// Retrieve the PDF blob
var pdfBlobArray = getPdfBlobs(ss.getId(),sheetId);
// Send the email + attachment
MailApp.sendEmail(recipients,subject,"Report attached.", {
htmlBody: htmlMessage,
attachments: pdfBlobArray
});
}
getPdfBlobs()实用函数
生成电子表格 PDF 的实用程序出现在 Convert all sheets to PDF with Google Apps Script 中。
这可以调整为返回一个 blob,其中包含您所追求的单张纸的 PDF。
您必须通过“资源 > 高级驱动器服务...”和开发者控制台启用 Advanced Drive Service。 (有关更多信息,请参阅this。)
注意:编辑嵌入在此函数中的 URL 参数支持对 PDF 输出的一些奇怪的自定义。
/**
* Get one or all sheets in a spreadsheet as PDF file blobs.
*
* From: https://stackoverflow.com/a/37149036/1677912
* Adapted from https://stackoverflow.com/a/30492812/1677912
*
* @param {String} optSSId (optional) ID of spreadsheet to export.
* If not provided, script assumes it is
* sheet-bound and opens the active spreadsheet.
* @param {String} optSheetId (optional) ID of single sheet to export.
* If not provided, all sheets will export.
*/
function getPdfBlobs( optSSId, optSheetId ) {
// If a sheet ID was provided, open that sheet, otherwise assume script is
// sheet-bound, and open the active spreadsheet.
var ss = (optSSId) ? SpreadsheetApp.openById(optSSId) : SpreadsheetApp.getActiveSpreadsheet();
// Get URL of spreadsheet, and remove the trailing 'edit'
var url = ss.getUrl().replace(/edit$/,'');
// Get array of all sheets in spreadsheet
var sheets = ss.getSheets();
// Loop through all sheets, generating PDF blobs.
var blobArray = [];
for (var i=0; i<sheets.length; i++) {
var sheet = sheets[i];
// If provided a optSheetId, only save it.
if (optSheetId && optSheetId !== sheet.getSheetId()) continue;
//additional parameters for exporting the sheet as a pdf
var url_ext = 'export?exportFormat=pdf&format=pdf' //export as pdf
+ '&gid=' + sheet.getSheetId() //the sheet's Id
// following parameters are optional...
+ '&size=letter' // paper size
+ '&portrait=true' // orientation, false for landscape
+ '&fitw=true' // fit to width, false for actual size
+ '&sheetnames=false&printtitle=false&pagenumbers=false' //hide optional headers and footers
+ '&gridlines=false' // hide gridlines
+ '&fzr=false'; // do not repeat row headers (frozen rows) on each page
var options = {
headers: {
'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()
}
}
var response = UrlFetchApp.fetch(url + url_ext, options);
var blob = response.getBlob().setName(ss.getName() + ' - ' + sheet.getName() + '.pdf');
// Add blob to our array
blobArray.push(blob);
}
// Return array of PDF blobs
return blobArray;
}
/**
* Dummy function for API authorization only.
* From: https://stackoverflow.com/a/37172203/1677912
*/
function forAuth_() {
DriveApp.getFileById("Just for authorization"); // https://code.google.com/p/google-apps-script-issues/issues/detail?id=3579#c36
}
1这可以进一步扩展为一个插件,这样脚本就不需要附加到特定的电子表格中。