4

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

4

1 回答 1

6

这类似于 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);
}
于 2013-02-01T01:16:41.210 回答