json - 通过自定义菜单从浏览器将 Google 表格数据下载为 JSON

有没有办法直接从 Google 表格下载 JSON,如下所示:

我想使用应用脚本创建自定义菜单。会有一个按钮可以从工作表数据创建 JSON 对象,完成后会立即将其下载为文件。 因此不涉及 GDrive 或其他应用程序,只有一个 Google 表格和一个应用程序脚本。

这有可能做到吗?我找不到这样的东西。

最佳答案

我相信你的目标如下。

  • 您想从自定义菜单运行脚本。
  • 您想将事件工作表下载为包含 JSON 数据的文件。
  • 示例 JSON 数据如下。
    • [{"a1": "a2", "b1": "b2"},{"a1": "a3", "b1": "b3"},,,]

在这种情况下,为了下载文件,需要使用 Javascript。为此,在此答案中,使用了一个对话框。所以这个示例脚本的流程如下。

  1. 从自定义菜单运行脚本。
  2. 打开一个对话框。
  3. 在对话框上运行 Javascript,并下载文件。
  4. 对话框关闭。

当上面的流程反射(reflect)到一个脚本中时,它变成如下。

示例脚本:

请将以下脚本复制并粘贴到脚本编辑器中,然后运行 ​​onOpen 或重新打开电子表格。这样,自定义菜单就创建好了。

Google Apps 脚本端: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};
}

HTML&Javascript 端: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>

引用资料:

  • Custom Menus in Google Workspace
  • Dialogs and Sidebars in Google Workspace Documents

https://stackoverflow.com/questions/66308153/

相关文章:

database - Mongo错误QueryExceededMemoryLimitNoDiskUs

python - 无法分割手写字符

java - 使用 LinkedHashMap 的字符串中的第一个唯一字符

c - 如何在不使用数组的情况下验证输入格式,例如输入 "OIL2932"

c++ - 如何在 constexpr if-else 链中导致静态错误?

debugging - 调试 : Couldn't match expected type ‘GHC

reactjs - 如何防止 Nivo 刻度轴文本(条形图)中的文本截断

common-lisp - 拆分格式字符串(格式 t ...)

angular - PrimeNG 报错 ConfirmationService has not b

regex - 计算 Perl 中字符串中非空白字符的数量