Simon GIS
Simon GIS

Reputation: 1055

Google App Script Import CSV to Google Sheets

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?

Upvotes: 1

Views: 4490

Answers (2)

luke
luke

Reputation: 524

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.

Upvotes: 1

Tanaike
Tanaike

Reputation: 201643

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:

Upvotes: 2

Related Questions