-->

Script import local CSV in Google Spreadsheet

2019-04-09 22:55发布

问题:

How do I import a CSV file from local hard drive in a Google Spreadsheet document I own? (I want to replicate via script the File-->Import command)

回答1:

This is similar to wrong answer with the DocList, but instead of using DocsList you can get the data directly out of the blob, parse it and then import it into a spreadsheet. I've only give a brief outline:

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