Google-sheets – Why doesn’t this script populate sheet after parsing data from CSV file

csvgoogle sheetsgoogle-apps-script

I got the below script which seems to work from time to time. It runs with no bugs reported, but it doesn't populate the sheet it is supposed to:

function importCSVFromWeb(url) {

  // Provide the full URL of the CSV file.
  var csvUrl = "Https...";
  var csvContent = UrlFetchApp.fetch(csvUrl).getContentText();
  var csvData = Utilities.parseCsv(csvContent);

  var sheet = SpreadsheetApp.getActiveSpreadSheet().getSheetByName('Entradas');
   if(sheet.getName()=='Entradas'){
  sheet.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);
   }
}

Best Answer

It rather depends on what the website specified by that URL returns. If it's down, disallows robots, or returns data in a format that's not expected by parseCsv, then something is going to break. Try inserting debugging messages, such as

function importCSVFromWeb(url) {

  // Provide the full URL of the CSV file.
  var csvUrl = "Https...";
  var csvContent = UrlFetchApp.fetch(csvUrl).getContentText();
  Logger.log(csvContent); // log for debugging, if used interactively
  var csvData = Utilities.parseCsv(csvContent);
  if (!csvData || !(csvData.length)) {
      MailApp.sendEmail('you', 'error report', 'could not parse data ' + csvContent); 
  }   // emailing bug report  

  var sheet = SpreadsheetApp.getActiveSpreadSheet().getSheetByName('Entradas');
  sheet.getRange(1, 1, csvData.length, csvData[0].length); 
}

The check if(sheet.getName()=='Entradas') was unnecessary since the sheet was obtained by that name.