脚本导入Google电子表格中的本地CSV

时间:2012-06-30 10:11:30

标签: google-apps-script google-sheets import-from-csv

如何在我拥有的Google电子表格文档中从本地硬盘导入CSV文件? (我想通过脚本复制文件 - >导入命令)

1 个答案:

答案 0 :(得分:5)

这类似于DocList的错误答案,但是您可以直接从Blob中获取数据,解析它然后将其导入电子表格,而不是使用DocsList。我只简要介绍一下:

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