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

修改Google脚本获取最新CSV文件时遇getBlob未定义错误求助

修正Google脚本中getBlob is not defined错误

我尝试修改脚本使其仅获取指定文件夹内的最新CSV文件,但运行时在代码let vs = Utilities.parseCsv(DriveApp.getFileById(arr[0].id),getBlob().getDataAsString());处报错Error: getBlob is not defined。原代码如下:

function runScript2() {
  const ss = SpreadsheetApp.getActive()
  const folder = DriveApp.getFolderById("1Hxxx");
  const files = folder.getFiles();
  const arr = [];

  while (files.hasNext()) {
    let file = files.next();  
 arr.push({name:file.getName(),id:file.getId(),mimetype:file.getMimeType(),date:file.getDateCreated()});
    //let fn = file.getName();
    //let fileID = file.getId();
    //let fileType = file.getMimeType();
  };
    //console.log(arr)
    arr.sort((a,b)=> {
      return new Date(b.date).valueOf() - new Date(a.date).valueOf();
    });
    //console.log(arr)

    let vs = Utilities.parseCsv(DriveApp.getFileById(arr[0].id),getBlob().getDataAsString());
    let sh = SpreadsheetApp.getActiveSheet();
    sh.clearContents();
    sh.getRange(1,1,vs.length, vs[0].length).setValues(vs);
}

错误原因

getBlob()是Google Drive文件对象的专属方法,直接调用getBlob()未指定所属文件对象,导致系统无法识别该方法,因此报错未定义。

修正后的代码

function runScript2() {
  const ss = SpreadsheetApp.getActive();
  const folder = DriveApp.getFolderById("1Hxxx");
  const files = folder.getFiles();
  const arr = [];

  while (files.hasNext()) {
    let file = files.next();
    // 仅收集CSV格式的文件,避免处理非CSV文件出错
    if (file.getMimeType() === "text/csv") {
      arr.push({
        name: file.getName(),
        id: file.getId(),
        mimetype: file.getMimeType(),
        date: file.getDateCreated()
      });
    }
  };

  // 检查文件夹中是否存在CSV文件,无文件时终止脚本并提示
  if (arr.length === 0) {
    SpreadsheetApp.getUi().alert("目标文件夹中未找到CSV文件");
    return;
  }

  // 按文件创建时间倒序排序,最新文件排在首位
  arr.sort((a, b) => new Date(b.date).valueOf() - new Date(a.date).valueOf());

  // 获取最新CSV文件对象,读取其内容
  const latestCsvFile = DriveApp.getFileById(arr[0].id);
  const csvContent = latestCsvFile.getBlob().getDataAsString();
  const vs = Utilities.parseCsv(csvContent);

  const sh = SpreadsheetApp.getActiveSheet();
  sh.clearContents();
  // 确保CSV内容非空再写入表格
  if (vs.length > 0) {
    sh.getRange(1, 1, vs.length, vs[0].length).setValues(vs);
  }
}

关键修改说明

  • 新增CSV文件过滤:只收集MIME类型为text/csv的文件,避免后续处理非CSV文件引发错误
  • 增加空数组判断:当文件夹中没有CSV文件时,弹出提示并终止脚本,防止后续代码报错
  • 修复getBlob()调用:先获取最新的文件对象,再调用该对象的getBlob()方法读取CSV内容,解决方法未定义的错误
  • 增加内容非空判断:确保CSV内容有效时再写入表格,避免空内容导致的写入错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 23:45:48