0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

1.GASを初めて触ってみる

Last updated at Posted at 2024-08-01

今日の目標!GASでスプレッドシートの値をHTML画面として表示する。

ちょっとかかわっているボランティア団体の情報管理を勉強がてらアプリ化したいなと思いまして、いろいろやってみる記録です。
GASはQiitaとかTwitterとかでちょっと見かけたくらいの知識なので、これから手探りで進めていきます!

0. 構成

かぎしっぽシステム構成.drawio.png

ボランティアメンバーはあまりITツール系に詳しくないので、スマホで操作は完結できるようにしたい。しかし、HPやInstagramを管理している人はPCで情報を扱いやすくしたい。
ということで、入力画面はスマホでも使いやすく、ベースのデータはスプレッドシート系で扱いすくしていきます。
カレンダーやフォームやLINEとも連携したい。。。

1.とりあえずHTMLファイルをアプリ上で見られるようにする

GoogleDriveからGASの新規作成をしてみる。
image.png

GASを新規作成して、とりあえず簡単なHTMLファイルのみ作成。

catDetails.html
<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <title>猫詳細</title>
  </head>
  <body>
    <h1>猫詳細</h1>
    <p>テストページ</p>
  </body>
</html>

Webアプリとしてデプロイする。
image.png

生成されたURLを開いてみると…
image.png

エラー。
何とかしてみます。
どうやら、gsファイルの方でdoGet()して、HTMLをリターンする必要があるみたい。

CatDetailsGS.gs
/** 
 * 詳細画面表示
 */
function doGet() {
  const template = HtmlService.createTemplateFromFile('CatDetails');
  const htmlOutput = template.evaluate();
  return htmlOutput;
}

デプロイしてみました!
image.png

何とか画面が出たのですが、、何度か試行錯誤した中で、URLが都度変わることがわかりました。URL変わると不便なので、変わらないようにしていきます!

2.URLが変わらないようなデプロイ方法にする!

デプロイの管理から、固定したいURLのバージョンを開く。
image.png

そのURLに対応するバージョンを変更すると、URLはそのままで開かれる内容が今回だとバージョン10に書き換えられるみたい。
image.png

3.スプレッドシートを出力する

とりあえず猫の情報を記載したスプレッドシートを作成します。
image.png

先人の力をお借りして・・・
image.png

でた!

こんなコードになりました。元のコードと違うのは「SpreadsheetApp.openByUrl(url);」の部分。開いているスプレッドシートを操作するわけではないのでURL指定に変更しました。

CatDetailsGS.gs
/** 
 * 詳細画面表示
 */
function doGet(e) {
  const cats = getAllRecords('猫マスタ');
  const template = HtmlService.createTemplateFromFile('CatDetails');
  template.deployURL = ScriptApp.getService().getUrl();
  template.formHTML = getFormHTML(e, cats);
  const htmlOutput = template.evaluate();
  return htmlOutput;
}

/** 
 * 詳細画面表示
 * https://uncle-gas.com/gas-html-display-dynamic/
 */
function getAllRecords(sheetName) {
  var url = 'https://docs.google.com/spreadsheets/🐈🐈🐈🐈🐈🐈🐈🐈/edit?usp=sharing';
  const ss = SpreadsheetApp.openByUrl(url);
  const sheet = ss.getSheetByName(sheetName);
  const values = sheet.getDataRange().getValues();
  const labels = values.shift();

  const records = [];
  for(const value of values) {
    const record = {};
    labels.forEach((label, index) => {
      record[label] = value[index];      
    });
    records.push(record);
  }

  return records;
}

/**
 * 表示用のHTMLを生成する
 */
function getFormHTML(e, cats, alert='') {
  let html = `
    <table class="table">
      <thead>
        <tr>
          <th scope="col">名前</th>
          <th scope="col">誕生日</th>
          <th scope="col">年齢</th>
        </tr>
      </thead>
      <tbody>
  `;

  for(const cat of cats) {
    const catName = cat['名前'];
    const catBirthday = cat['誕生日'];
    const catAge = cat['年齢'];
    html += `<tr>`;
    html += `<td>${catName}</td>`;
    html += `<td>${catBirthday}</td>`;
    html += `<td>${catAge}</td>`;
    html += `</tr>`;
  }

  html += `</tbody>`;
  html += `</table>`;

  return html;
}
catDetails.html
<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <title>猫詳細</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
  </head>
  <body>
    <div>猫なまえ</div>
    <div>誕生日</div>
    <div>保護日</div>
    <div>トライアル開始日</div>
    <div>正式譲渡日</div>
    <div>預かりさん</div>
    <div class="container" style="max-width: 600px;">
      <h2 class="text-center m-4">猫詳細</h2>
      <form class="mb-5" method="POST" action="<?= deployURL ?>">
        <? output._ = formHTML ?>
        <button type="submit" class="btn btn-outline-primary" name="confirm" value="true">+</button>
      </form>
    </div>
  </body>
</html>

今日はここまで。

0
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?