Exceeded maximum execution time during Import of CSV

浪尽此生 提交于 2019-12-13 07:57:56

问题


I followed Google's Interacting With Your Docs List tutorial on how to write a script on importing CSV files. After a lot of help I got it to work. However when I try to copy it, or modify it in any way, it times out with the error message:

Exceeded maximum execution time.

...and doesn't run. Why would this be happening?

This is the importFromCSV() function from the tutorial:

function importFromCSV() {
  var fileName = Browser.inputBox("Enter the name of the file in your Docs List to import (e.g. myFile.csv):");

 var files = DocsList.getFiles();
  var csvFile = "";

  for (var i = 0; i < files.length; i++) {
    if (files[i].getName() == fileName) {
      csvFile = files[i].getContentAsString();
      break;
    }
  }
  var csvData = CSVToArray(csvFile, ",");
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  for (var i = 0; i < csvData.length; i++) {
    sheet.getRange(i+1, 1, 1, csvData[i].length).setValues(new Array(csvData[i]));
  }
}

回答1:


The CSV import example does a CSVToArray call for every row. That's slow.

Check out the advice in the Best Practices Doc. The first piece of guidance is to reduce calls to other services; change the example to update all rows of an array, and then call var arrData = [[]] just once, and you will vastly improve the performance.

Replace this:

for (var i = 0; i < csvData.length; i++) {
  sheet.getRange(i+1, 1, 1, csvData[i].length).setValues(new Array(csvData[i]));
}

With this:

sheet.clear();

var numRows = csvData.length;
var numCols = csvData[0].length; // assume all rows are same width

// Make a single call to spreadsheet API to write values to sheet.
sheet.getRange(1, 1, numRows, numCols).setValues( csvData );
SpreadsheetApp.flush();

I also found that I needed to change a couple of lines in var arrData = new Array(), instead of declaring the arrays like this: setValues(), I used this: setValues. It shouldn't matter (in JavaScript), but it did (in Google Apps Script).



来源:https://stackoverflow.com/questions/14691051/exceeded-maximum-execution-time-during-import-of-csv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!