Skip to content

Instantly share code, notes, and snippets.

@dommmel
Created August 2, 2015 13:28
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dommmel/b7e0f52a046b392c9c93 to your computer and use it in GitHub Desktop.
Save dommmel/b7e0f52a046b392c9c93 to your computer and use it in GitHub Desktop.
Google Apps Script to upload and import a CSV File into a Google Spreadsheet
// http://stackoverflow.com/questions/11273268/script-import-local-csv-in-google-spreadsheet
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var csvMenuEntries = [{name: "Upload CSV file", functionName: "doGet"}];
ss.addMenu("CSV", csvMenuEntries);
}
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);
SpreadsheetApp.getActiveSpreadsheet().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
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
for (var i = 0; i < values.length; i++) {
sheet.getRange(i+1, 1, 1, values[i].length).setValues(new Array(values[i]));
}
}
@engrki
Copy link

engrki commented Jul 18, 2018

Hi,
Instead of Row Number 31 to 35 in your script use the below code.

` try{
var A = sheet.getRange("A1:A").getValues();
var RW = A.filter(String).length;
RW = RW +1;

   sheet.getRange('A'+ RW +':C' + (values.length + (RW -1))).setValues(values); 
  
  } catch (e){
    Logger.log(e)
  }`

The above code will perform two things.
1 - It will write the full array in one shot on the sheet
2 - It will write the new record on non-empty row just below to the existing record to avoid over write on the existing record.

Note: Instead of A to C You can change the column range. e.g 'A'+ RW +':Z' + (values.length + (RW -1))

@SuperDev820
Copy link

Exception: UiApp has been deprecated. Please use HtmlService instead.
I get this error.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment