Skip to content

Instantly share code, notes, and snippets.

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
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.createSubmitButton('Start Upload'));
var form = app.createFormPanel();
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]));
Copy link

I have implemented doGet and doPost for uploading .csv files for a spreadsheet.
On Linux, it works perfect, but when running on Windows (XP and 10) fileBlob in doPost is empty.

In Linux I use Chromium and on Windows Chrome. Is that a known problem?
Kind regards Carsten Juul

Copy link

engrki commented Jul 18, 2018

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){

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))

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