You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Sheets发送指定范围为PDF邮件出现TypeError错误如何解决

问题修复方案

错误原因

  • SpreadsheetApp.getActiveSpreadsheet().getRange()返回的是单元格范围对象,该对象不支持getAs()方法,只有电子表格、工作表、Blob类对象才有该导出方法,因此触发类型错误。

修复思路

要导出指定范围为PDF,需要调用Google Sheets的原生导出接口,通过参数指定导出的工作表和单元格范围,再将返回的Blob作为附件发送。

完整修改后代码

function sendReport() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  // 隐藏Responses工作表
  ss.getSheetByName("Responses").hideSheet();
  const formSheet = ss.getSheetByName("Form");
  formSheet.activate();
  const recipient = formSheet.getRange('L2').getValue();
  const ssId = ss.getId();
  const formSheetGid = formSheet.getSheetId();
  // 构造PDF导出链接,指定导出范围为Form表A5:H25
  const exportUrl = `https://docs.google.com/spreadsheets/d/${ssId}/export?` +
    `exportFormat=pdf&` +
    `gid=${formSheetGid}&` +
    `range=A5:H25&` + // 指定导出范围
    `size=A4&` + // 纸张大小可自定义
    `portrait=true&` + // true为纵向,false为横向
    `fitw=true&` + // 适配页面宽度
    `gridlines=false&` + // 是否显示网格线
    `printnotes=false&` + // 是否导出备注
    `top_margin=0.5&bottom_margin=0.5&left_margin=0.5&right_margin=0.5`; // 边距单位为英寸
  // 发起导出请求
  const pdfBlob = UrlFetchApp.fetch(exportUrl, {
    headers: {
      'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()
    }
  }).getBlob().setName("Monthly sales report.pdf");

  // 构造邮件参数
  const message = {
    to: recipient,
    subject: "月度销售报表",
    body: "各位团队成员好:\n\n请查收附件中的月度报表。\n\n谢谢\nBob",
    name: "Bob",
    attachments: [pdfBlob]
  };
  MailApp.sendEmail(message);
  // 恢复Responses工作表显示
  ss.getSheetByName("Responses").activate();
  ss.getSheetByName("Responses").showSheet();// 不需要恢复显示可删除此行
}

注意事项

  • 首次运行需要授权脚本访问你的Google Sheet和邮件权限
  • 导出参数可以根据你的需求调整,比如纸张大小、是否显示网格线、边距等

内容的提问来源于stack exchange,提问作者NOOR UL KARIM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 12:48:01