如何编写一个脚本,让我在单击自定义菜单时可以从 Google 电子表格中的本地驱动器选择并上传 CSV 文件? (我想通过脚本复制文件-->导入命令,但在打开时呈现的新菜单中)。
这里有一个类似的问题,但答案使用了一种现已弃用的方法。脚本在 Google 电子表格中导入本地 CSV https://stackoverflow.com/questions/11273268/script-import-local-csv-in-google-spreadsheet
已弃用的答案
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);
}
我相信您的目标如下。
- 您想要通过从 Google 电子表格的自定义菜单执行脚本来将 CSV 数据上传到活动工作表。
在这种情况下,下面的示例脚本怎么样?
示例脚本:
Google Apps 脚本端:Code.gs
请将以下脚本作为脚本复制并粘贴到脚本编辑器中。
function onOpen() {
SpreadsheetApp.getUi().createMenu("sample").addItem("import CSV", "importCsv").addToUi();
}
function importCsv(e){
if (!e) {
SpreadsheetApp.getUi().showModalDialog(HtmlService.createHtmlOutputFromFile("index"), "sample");
return;
}
const csv = Utilities.parseCsv(Utilities.newBlob(...e).getDataAsString());
const sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange(sheet.getLastRow() + 1, 1, csv.length, csv[0].length).setValues(csv);
}
HTML 和 JavaScript 方面:index.html
请将以下脚本以 HTML 格式复制并粘贴到脚本编辑器中。
<form><input type="file" name="file" onchange="importCsv(this.parentNode)" accept=".csv,text/csv"></form>
<script>
function importCsv(e) {
const file = e.file.files[0];
const f = new FileReader();
f.onload = d => google.script.run.withSuccessHandler(google.script.host.close).importCsv([[...new Int8Array(d.target.result)], file.type, file.name]);
f.readAsArrayBuffer(file);
}
</script>
Testing:
当您测试上述脚本时,请运行onOpen
或重新打开电子表格。这样就可以看到自定义菜单了。当您从自定义菜单中选择“导入 CSV”时,将打开一个对话框。当您从本地 PC 选择 CSV 文件时,CSV 数据将导入到活动工作表中。
Note:
- 这是一个简单的示例脚本。所以请根据您的实际情况进行修改。
参考:
- Google Workspace 中的自定义菜单 https://developers.google.com/apps-script/guides/menus
- Google Workspace 文档中的对话框和侧边栏 https://developers.google.com/apps-script/guides/dialogs
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)