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

如何用Google Apps Script实现谷歌表格全列PDF导出并邮件通知?

谷歌表格多列PDF导出及邮件通知脚本优化

问题解决说明

  1. 包含A到AZ列导出:通过调整导出URL的c2参数为51(A列索引为0,AZ列对应索引51),确保所有目标列被包含;同时动态获取工作表最后一行,避免导出大量空白行。
  2. 实现“正常/拆分”模式:通过URL参数fitw控制:
    • fitw=true:对应手动导出的“正常”模式,内容自动适应页面宽度
    • fitw=false:对应手动导出的“拆分”模式,内容按实际宽度分页,超出部分自动拆到下一页

优化后的完整代码

function refreshAndSendEmail() {
  const ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/xxxxx');
  const tabsToSnapshot = ['a', 'b']; // 替换为需要导出的工作表名称
  const pdfFitMode = true; // true=正常模式(适应宽度),false=拆分模式(按实际宽度分页)

  tabsToSnapshot.forEach(tabName => {
    const dataSheet = ss.getSheetByName(tabName);
    if (dataSheet) {
      refreshDataSourcesForSheet(dataSheet);
    } else {
      console.log(`${tabName} 未找到`);
    }
  });

  const pdfBlob = generatePDF(ss, tabsToSnapshot, pdfFitMode);
  sendEmailWithAttachment(pdfBlob);
}

function refreshDataSourcesForSheet(sheet) {
  const dataSources = sheet.getDataSourceTables();
  dataSources.forEach(dataSource => {
    dataSource.refreshData();
    console.log(`${dataSource.getName()} 最后刷新时间: ${dataSource.getStatus().getLastRefreshTime()}`);
  });
}

function generatePDF(ss, sheetNames, fitWidth) {
  const spreadsheetId = ss.getId();
  const pdfBlobs = [];

  for (const sheetName of sheetNames) {
    const sheet = ss.getSheetByName(sheetName);
    if (!sheet) continue;

    // 设置导出范围:A列到AZ列,从第1行到数据最后一行
    const firstRow = 0; // 对应工作表第1行(0-based索引)
    const firstCol = 0; // 对应A列
    const lastCol = 51; // 对应AZ列(A=0,AZ为第52列,索引51)
    const lastRow = sheet.getLastRow() - 1; // 转换为0-based索引,避免导出空白行

    const url = `https://docs.google.com/spreadsheets/d/${spreadsheetId}/export` +
      `?format=pdf` +
      `&size=7` +
      `&fzr=true` +
      `&portrait=true` +
      `&fitw=${fitWidth}` + // 控制适应宽度模式
      `&gridlines=false` +
      `&printtitle=false` +
      `&top_margin=0.5` +
      `&bottom_margin=0.25` +
      `&left_margin=0.5` +
      `&right_margin=0.5` +
      `&sheetnames=false` +
      `&pagenum=UNDEFINED` +
      `&attachment=true` +
      `&gid=${sheet.getSheetId()}` + // 指定导出的工作表ID
      `&r1=${firstRow}&c1=${firstCol}&r2=${lastRow}&c2=${lastCol}`;

    const options = {
      headers: {
        Authorization: 'Bearer ' + ScriptApp.getOAuthToken()
      }
    };

    const response = UrlFetchApp.fetch(url, options);
    pdfBlobs.push(response.getBlob());
  }

  // 合并多个工作表的PDF为单个文件
  if (pdfBlobs.length === 1) {
    return pdfBlobs[0].setName('数据快照.pdf');
  } else {
    const tempFolder = DriveApp.createFolder('临时PDF合并');
    const files = pdfBlobs.map((blob, idx) => tempFolder.createFile(blob.setName(`工作表${idx+1}.pdf`)));
    let mergedPdf = files[0].getAs('application/pdf');
    for (let i = 1; i < files.length; i++) {
      mergedPdf.setContent(mergedPdf.getBytes().concat(files[i].getAs('application/pdf').getBytes()));
    }
    tempFolder.setTrashed(true); // 清理临时文件
    return mergedPdf.setName('数据快照.pdf');
  }
}

function sendEmailWithAttachment(pdfBlob) {
  const recipient = 'your-email@example.com'; // 替换为收件人邮箱
  const subject = '数据快照已生成';
  const body = '请查看附件中的最新数据快照。';
  
  MailApp.sendEmail({
    to: recipient,
    subject: subject,
    body: body,
    attachments: [pdfBlob]
  });
}

关键修改点

  • 新增pdfFitMode参数,一键切换“正常”/“拆分”导出模式
  • 固定导出列范围到AZ列,同时动态获取数据最后一行,减少空白内容
  • 支持导出多个指定工作表,并自动合并为单个PDF文件
  • 修正原代码未指定工作表ID的问题,确保只导出目标工作表

内容的提问来源于stack exchange,提问作者Skylar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 09:15:56