-->

Exceeded maximum execution time during Import of C

2019-09-19 09:58发布

问题:

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).