Google 电子表格中的 PDF 格式的应用程序脚本电子邮件

Google App Script Email as PDF from Spreadsheet

我下面用于生成 PDF 附件的代码工作正常,但它们发送了传播中的所有数据sheet。

任何人都可以像我的代码一样只发送指定的传播sheet sheet“电子邮件”而不是所有 sheets 吗? 谢谢

function SendEmail() {

  try {
    var ss  = SpreadsheetApp.getActive();
    var url = "https://docs.google.com/feeds/download/spreadsheets/Export?key=" + ss.getId() + "&exportFormat=pdf";

    var params = {
      method      : "get",
      headers     : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
      muteHttpExceptions: true
    };

    var blob = UrlFetchApp.fetch(url, params).getBlob();
    var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Email')
    var subjectrange = sheet.getRange("A20");
    var subjectdata = subjectrange.getValues();
    var emailranges=sheet.getRange('E14');
    var emaildata=emailranges.getValue();
    var username=ss.getSheetId();
    blob.setName(ss.getName()+ ".pdf");
    var confirm = Browser.msgBox('Send Email Confirmation','Are you sure you want to send this mail for booking request ?', Browser.Buttons.OK_CANCEL);
    if(confirm=='ok') {
      MailApp.sendEmail(emaildata, subjectdata, " Attachment file is:  \n"  +subjectdata+ "- \n Kindly reply your booking to this email . \n Thank you - ADS Co., Ltd", {attachments: [blob]}) };} catch (f) {Logger.log(f.toString());
    }
}

回答

如果您不想导出一些 sheets,您可以 hide them. Furthermore, you can export a Spreadsheet with the method getBlob. Once you have made the export, you can undo the hide

假设两张小代码

var sheet = ss.getSheetByName('Unwanted Sheet')
sheet.hideSheet()
var blob = ss.getBlob()
blob.setName(ss.getName())
sheet.showSheet()

使用多张纸的完整代码

function exportSheet(sheetName) {    
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheets = ss.getSheets();
  for (var i = 0; i < sheets.length; i++) {
    if (sheets[i].getSheetName() !== sheetName) {
      sheets[i].hideSheet()
    } 
  }
  var blob = ss.getBlob()
  blob.setName(ss.getName())
  for (var i = 0; i < sheets.length; i++) {
    sheets[i].showSheet()
  }
}

一些小技巧

  • 你不必在blob名称中添加.pdf,它已经理解它是一个pdf文件并且扩展名会自动出现
  • 您可以使用 GmailApp service instead of MailApp,因为它更通用且功能更多。使用 MailApp 的主要原因是它不要求开发人员是 Gmail 用户。

参考