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

Google Sheets遍历下拉列表所有选项循环生成PDF的脚本咨询

Google Sheets下拉列表选项批量导出PDF脚本

以下是可直接使用的完整实现脚本:

function loopExportPdfByDropdown() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const interfaceSheet = ss.getSheetByName("Interface");
  const a2Cell = interfaceSheet.getRange("A2");
  const b2Cell = interfaceSheet.getRange("B2");

  // 配置项:替换为你的谷歌云盘目标文件夹ID
  const folderID = "###GOOGLE DRIVE FOLDER ID###";
  const targetFolder = DriveApp.getFolderById(folderID);

  // PDF导出配置,可根据需求调整参数
  const exportOptions =  'exportFormat=pdf&format=pdf' 
    + '&size=A4'                      
    + '&portrait=true'              
    + '&scale=4'            
    + '&fith=true&source=labnol'        
    + '&top_margin=0.05'
    + '&bottom_margin=0.05'
    + '&left_margin=1.00'
    + '&right_margin=0.25'
    + '&sheetnames=false&printtitle=false'
    + '&pagenumbers=false&gridlines=false'
    + '&fzr=false'                      
    + '&gid=125740569'; // 替换为你要导出的工作表GID

  const requestParams = {
    method:"GET",
    headers:{"authorization":"Bearer "+ ScriptApp.getOAuthToken()}
  };
  const sheetBaseUrl = ss.getUrl().replace(/edit.*$/, '');

  // 获取A2单元格下拉列表的所有选项
  const dataValidation = a2Cell.getDataValidation();
  if (!dataValidation || dataValidation.getType() !== SpreadsheetApp.DataValidation.Type.VALUE_RANGE) {
    SpreadsheetApp.getUi().alert("A2单元格未设置下拉列表,请检查配置");
    return;
  }
  const dropdownOptions = dataValidation.getCriteriaValues()[0].getValues().flat().filter(option => option);

  // 遍历所有选项执行导出逻辑
  for (let option of dropdownOptions) {
    // 给A2赋值当前选项
    a2Cell.setValue(option);
    // 等待表格所有公式计算完成
    SpreadsheetApp.flush();
    Utilities.sleep(500); // 复杂计算场景可适当调大等待时间,单位毫秒

    // 检查B2是否非空,非空才导出PDF
    if (b2Cell.getValue() !== "") {
      const pdfBlob = UrlFetchApp.fetch(sheetBaseUrl + exportOptions, requestParams).getBlob();
      const fileName = `${option}.pdf`; // 用当前选项作为PDF文件名,可自定义命名规则
      targetFolder.createFile(pdfBlob.setName(fileName));
    }
  }

  SpreadsheetApp.getUi().alert("所有选项处理完成");
}

使用说明

  • 运行前请先替换脚本中folderID为你自己的Google Drive目标文件夹ID,文件夹ID可以从文件夹的浏览器访问链接中提取
  • 确认exportOptions中的gid参数为你要导出的工作表对应ID,打开目标工作表后浏览器地址栏末尾的gid参数值即可直接使用
  • 确认Interface为你实际使用的工作表名称,如不一致修改为对应名称即可
  • 脚本首次运行需要授权,遇到风险提示时点击「高级」-「继续前往(项目名称)」即可完成授权
  • 如果表格计算逻辑复杂,导出的PDF内容不匹配,可以适当调大Utilities.sleep(500)里的等待时间

注意事项

  • Google Apps Script单次运行最大时长为6分钟,如下拉选项数量超过500个建议分批次处理
  • 脚本导出的PDF仅会保存在你指定的Drive文件夹中,不会额外存储到其他位置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 13:15:02