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