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

如何在Google Sheets中用Apps Script构建带变量URL每日导入数据

解决Google Sheets自动抓取前一日数据的日期变量问题

问题分析

你现有代码的核心问题有两个:

  • JavaScript的getMonth()返回0-11的数值(11月对应10),直接拼接会导致月份错误
  • 日期/月份为个位数时(如5号、3月),无法生成DD.MM.YYYY要求的两位格式,会破坏URL结构

修正后的代码

function TagesdurchschnittDeutschland() {
  const yesterday = new Date();
  yesterday.setDate(yesterday.getDate() - 1);
  
  // 处理日期格式:DD.MM.YYYY
  const day = String(yesterday.getDate()).padStart(2, '0');
  const month = String(yesterday.getMonth() + 1).padStart(2, '0');
  const year = yesterday.getFullYear();
  
  const url = `https://www.benzinpreis.de/statistik.phtml?o=4&so=b.order_total&cnt=50&mystatart=LKR&mystat=DAY${day}.${month}.${year}+00%3A00%3A00`;
  
  const sheet = SpreadsheetApp.getActive().getSheetByName('TagesdurchschnittDeutschland');
  sheet.getRange('A1').setFormula(`=IMPORTHTML("${url}"; "table"; 5)`);
}

关键改进点

  • 月份修正:给getMonth()结果加1,将0基数值转为实际月份
  • 补前导零:用padStart(2, '0')确保日期和月份始终是两位数字,符合URL要求的格式
  • 代码简化:去掉不必要的activate()操作,直接定位工作表和单元格,提升运行效率

自动运行设置

要实现每日自动抓取,你可以给这个函数设置时间驱动触发器:

  1. 打开Google Sheets,点击菜单栏的「扩展程序」→「Apps脚本」
  2. 在脚本编辑器界面,点击左侧的「触发器」图标(闹钟样式)
  3. 点击「添加触发器」,设置:
    • 选择要运行的函数:TagesdurchschnittDeutschland
    • 选择事件源:「时间驱动」
    • 选择时间类型:「日计时器」
    • 选择时间窗口:比如「上午6点到7点」(确保前一日数据已生成)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 12:31:00