Created
August 2, 2015 13:28
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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])); | |
} | |
} |
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))
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
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