您不能getAs(MimeType.PDF)单独将工作表内容转换为 pdf
将工作表范围作为 pdf 附件发送的一种方法是首先将其转换为 pdf blob,正如 Alan Wells 在 JPV 链接的帖子中所执行的那样。
基于此转换,您可以修改代码如下:
var ss = SpreadsheetApp.getActiveSpreadsheet();
function sendReport() {
var sheetTabNameToGet = "Form";
var range = "A5:H25";
var pdfBlob = exportRangeToPDf(range, sheetTabNameToGet);
var message = {
to: ss.getSheetByName(sheetTabNameToGet).getRange('L2').getValue(),
subject: "Monthly sales report",
body: "Hi team,\n\nPlease find the monthly report attached.\n\nThank you,\nBob",
name: "Bob",
attachments: [pdfBlob.setName("Monthly sales report")]
}
MailApp.sendEmail(message);
}
function exportRangeToPDf(range, sheetTabNameToGet) {
var blob,exportUrl,options,pdfFile,response,sheetTabId,ssID,url_base;
ssID = ss.getId();
sh = ss.getSheetByName(sheetTabNameToGet);
sheetTabId = sh.getSheetId();
url_base = ss.getUrl().replace(/edit$/,'');
exportUrl = url_base + 'export?exportFormat=pdf&format=pdf' +
'&gid=' + sheetTabId + '&id=' + ssID +
'&range=' + range +
'&size=A4' + // paper size
'&portrait=true' + // orientation, false for landscape
'&fitw=true' + // fit to width, false for actual size
'&sheetnames=true&printtitle=false&pagenumbers=true' + //hide optional headers and footers
'&gridlines=false' + // hide gridlines
'&fzr=false'; // do not repeat row headers (frozen rows) on each page
options = {
headers: {
'Authorization': 'Bearer ' + ScriptApp.getOAuthToken(),
}
}
options.muteHttpExceptions = true;//Make sure this is always set
response = UrlFetchApp.fetch(exportUrl, options);
if (response.getResponseCode() !== 200) {
console.log("Error exporting Sheet to PDF! Response Code: " + response.getResponseCode());
return;
}
blob = response.getBlob();
return blob;
}