首页 > 解决方案 > 导致 DriveApp.getFileById + Utilities.parseCsv 执行速度大幅下降的原因

问题描述

CSV文件通常有大约 10 行的值,它很小、很轻,但即便如此,所有执行都需要 200 秒才能将CSV文件中的值导入电子表格。

什么可能导致这种情况,我应该在代码中进行哪些更改以使其快速运行?

在此处输入图像描述

function ImportWebData() {
  const cleansheet = SpreadsheetApp.getActive().getSheetByName('ImportWebData');
  cleansheet.getRange('A1:Z' + cleansheet.getMaxRows()).clear({contentsOnly: true, skipFilteredRows: true});

  var sheet = SpreadsheetApp.getActive().getSheetByName('ImportWebData');
  var file = DriveApp.getFileById("1aYQLX-67EFJKbGy9TFnis1vjtxiro3r8");
  var csvData = Utilities.parseCsv(file.getBlob().getDataAsString());
  sheet.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);
}

注:Drive API活跃于Google Advanced Services

标签: google-apps-scriptgoogle-sheets

解决方案


我通过不使用 getMaxRows() 避免了清除可能不存在的数据的不必要步骤,我只使用了 sh.getLastRow(); 我可能已经使用 getLastColumn() 来获取数据,但我不知道文件中的内容。

function ImportWebData() {
  const ss = SpreadsheetApp.getActive();
  const sh1 = ss.getSheetByName('ImportWebData');
  sh1.getRange(1,1,sh1.getLastRow(),26).clear({contentsOnly: true, skipFilteredRows: true});
  var file = DriveApp.getFileById("1aYQLX-67EFJKbGy9TFnis1vjtxiro3r8")
  var csvData = Utilities.parseCsv(file.getBlob().getDataAsString());
  sh1.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);
}

我猜你把它公开了,它在几秒钟内就运行了


推荐阅读