mar*_*llo 3 json google-apps google-sheets google-apps-script google-sheets-api
有没有办法直接从 Google Sheet 下载 JSON,如下所示:

我想使用应用程序脚本创建自定义菜单。会有一个按钮可以从工作表数据创建 JSON 对象,完成后会立即将其下载为文件。因此,不涉及 GDrive 或其他应用程序,只有 Google 表格和应用程序脚本。
这有可能做到吗?我找不到这样的东西。
我相信你的目标如下。
[{"a1": "a2", "b1": "b2"},{"a1": "a3", "b1": "b3"},,,]在这种情况下,为了下载文件,需要使用Javascript。为此,在这个答案中,使用了一个对话框。所以这个示例脚本的流程如下。
当上述流程反映到脚本中时,就会变成如下所示。
请将以下脚本复制并粘贴到脚本编辑器中,然后运行onOpen或重新打开电子表格。至此,自定义菜单就创建完成了。
Code.gs请将以下脚本作为 Google Apps 脚本复制并粘贴到脚本编辑器中。
function onOpen() {
SpreadsheetApp.getUi().createMenu('Custom Menu').addItem('Export to JSON', 'download').addToUi();
}
function download() {
const html = HtmlService.createHtmlOutputFromFile("index");
SpreadsheetApp.getUi().showModalDialog(html, "sample");
}
function downloadFile() {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
const [header, ...values] = sheet.getDataRange().getValues();
const obj = values.map(r => r.reduce((o, c, j) => Object.assign(o, {[header[j]]: c}), {}));
const filename = `${sheet.getSheetName()}.txt`;
const blob = Utilities.newBlob(JSON.stringify(obj), MimeType.PLAIN_TEXT, filename);
return {data: `data:${MimeType.PLAIN_TEXT};base64,${Utilities.base64Encode(blob.getBytes())}`, filename: filename};
}
Run Code Online (Sandbox Code Playgroud)
index.html请将以下脚本作为 HTML 复制并粘贴到脚本编辑器中。
<script>
google.script.run
.withSuccessHandler(({ data, filename }) => {
if (data && filename) {
const a = document.createElement("a");
document.body.appendChild(a);
a.download = filename;
a.href = data;
a.click();
}
google.script.host.close();
})
.downloadFile();
</script>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4375 次 |
| 最近记录: |