'Google App Script to imitate File - Import csv file into a sheet using a custom menu item

How do I write a script that can let me select and upload a CSV file from local drive in a Google Spreadsheet when clicking on a custom menu ? (I want to replicate via script the File-->Import command but in a new menu being rendered onOpen).

There's a similar question here, but the answer uses a method that is now deprecated. Script import local CSV in Google Spreadsheet

Deprecated answer

function doGet(e) {
  var app = UiApp.createApplication().setTitle("Upload CSV to Sheet");
  var formContent = app.createVerticalPanel();
  formContent.add(app.createFileUpload().setName('thefile'));
  formContent.add(app.createSubmitButton('Start Upload'));
  var form = app.createFormPanel();
  form.add(formContent);
  app.add(form);
//  return app;
  SpreadsheetApp.getActiveSpreadsheet().show(app);// show app 
}

function doPost(e) {
  // data returned is a blob for FileUpload widget
  var fileBlob = e.parameter.thefile;

  // parse the data to fill values, a two dimensional array of rows
  // Assuming newlines separate rows and commas separate columns, then:
  var values = []
  var rows = fileBlob.contents.split('\n');
  for(var r=0, max_r=rows.length; r<max_r; ++r)
    values.push( rows[r].split(',') );  // rows must have the same number of columns

  // Using active sheet here, but you can pull up a sheet in several other ways as well
  SpreadsheetApp.getActiveSheet()
                .getRange( 1, 1, values.length, values[0].length )
                .setValues(values);
}


Solution 1:[1]

Instead of uploading it from local, it would be simpler to upload it from Google Drive.

Check-out the below code:

function importCSVFromGoogleDrive() {

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

}

This copies the data from "file.csv" in your Google Drive to the Sheet named "TEST" in your Spreadsheet.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gangula