LoginSignup
7
1

More than 3 years have passed since last update.

Google スプレッドシートから複数のCSVをローカルに保存するスクリプト

Posted at

Google スプレッドシートから複数の CSV を書き出す際、
シートごとに「ファイル」>「ダウンロード」>「カンマ区切りの値」とする必要があった。
まとめてダウンロードできるようにして手間を省くため書いたもの。

先行事例として下記の記事を参考にした。
GoogleAppsScript JavaScriptを用いてCSVをローカルに書き出す実装 - Qiita

参考記事のスクリプトだと GAS 側から関数一回呼び出して、文字列で返り値を受け取っていた。

var content = <?= getData(); ?>;

配列を HTML 側で受け取りループ回して CSV 吐き出すほうがシンプルなため
google.script.run.withSuccessHandler を使用。

実装

code.gs
// メニューバーにカスタムメニュー追加
function onOpen() {
  const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  const entries = [
    {
      name: "CSV出力",
      functionName: "csvDownload",
    },
  ];
  spreadsheet.addMenu("その他", entries);
}

// ポップアップ起動
function csvDownload() {
  const html = HtmlService.createTemplateFromFile("dialog").evaluate();
  SpreadsheetApp.getUi().showModalDialog(html, "ダウンロード");
}

// HTML側でスプレッドシートの中身取得&整形
function getData() {
  // スプレッドシートの値を取得
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
  const values = sheet.getDataRange().getValues();

  // 整形処理
  const dataList = [{
    title: "CSVのファイル名",
    body: "CSVの中身文字列",
  },...]
  return dataList;
}
dialog.html
<!DOCTYPE html>
<html>
  <head>
    <base target="_top" />
    <script>
      window.onload = () => {
        handleDownload();
      }
      function handleDownload() {
        google.script.run.withSuccessHandler((dataList) => {
          dataList.forEach(data => {
            const blob = new Blob([ table.body ], { "type" : "text/csv"});
            const link = document.createElement('a');
            link.download = `${table.title}.csv`;
            link.href = window.URL.createObjectURL(blob);
            link.click();
          });
          google.script.host.close();
        }).getData();
      }
    </script>
  </head>
</html>

参考

Class google.script.run (Client-side API)  |  Apps Script

7
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
1