Google App Script Import CSV to Google Sheets

Viewed 2488

I have a Google Sheet which i want to import a CSV File stored in my drive.

this is my code:

function importCSVFromGoogleDrive() {

  var file = DriveApp.getFilesByName("file.csv").next();
  var csvData = Utilities.parseCsv(file.getBlob().getDataAsString());
  var sheet = SpreadsheetApp.setActiveSheet(sheet.getSheetByName('TEST'))
  sheet.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);

}

I get error "TypeError: Cannot read property 'getSheetByName' of undefined". I would like to import my data of the CSV into the "TEST" Tab. How i can fix this?

2 Answers

I think that when I saw your script, sheet of sheet.getSheetByName('TEST') is not declared. If the sheet of sheet name of TEST is existing in the Spreadsheet, how about the following modification?

From:

var sheet = SpreadsheetApp.setActiveSheet(sheet.getSheetByName('TEST'))

To:

var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('TEST');

or

var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('TEST').activate();

Reference:

Don't think this question is active anymore, but I'll leave this here for anybody who might benefit from it.

The .next() at the end of the third line of code ( var file = DriveApp.getFilesByName("file.csv").next();) is unnecessary because of Google Apps Script's new V8 runtime. The code to copy only needs a legitimate txt or csv file.

Related