LoginSignup
2
3

More than 1 year has passed since last update.

GASでスプレッドシートに自動採番を追加する

Last updated at Posted at 2022-10-20

概要

バックエンド開発1

バックエンド開発で作成したGASに、自動採番を追加する方法です。
uuidを追加する方法と通し番号を追加する方法を記述します。

uuid追加

uuidを振る方法です。

8e96cb4c-9177-4ffe-83c9-53f4ccb53ba2 といった形式のidが振られます。

uuidはUtilities.getUuid()で取得できます。

コード.gs

const doPost = (e) => {

    //値の受取り
    const name = e.parameter.name ? e.parameter.name : "";
    const email = e.parameter.email ? e.parameter.email : "";
    const body = e.parameter.body ? e.parameter.body : "";

    //エラー処理
    const email_exp = /^[a-z0-9.]+@[a-z0-9.]+\.[a-z]+$/;
    const body_exp = /^.{1,10}$/;
 
    //問題があればエラーを返す(なければ処理を継続)
    if(name == ""|| !email_exp.test(email) || !body_exp.test(body)){
      return ContentService.createTextOutput(JSON.stringify({ message: "validation error!" }));
    }

+    //UUID取得
+  const uuid = Utilities.getUuid();

    //スプレッドシートの準備
    const ss = SpreadsheetApp.getActiveSpreadsheet();
    const sheet = ss.getSheetByName("シート1");

    //シートの一番下の行に追加
-   sheet.appendRow([name, email, body, new Date()]);
+   sheet.appendRow([uuid,name, email, body, new Date()]);

    //応答
    return ContentService.createTextOutput(JSON.stringify({ message: "success!" }));
}

通し番号

1から通し番号を振る方法です。
追加する前の値を確認して、+1した値を追加していくという方法です。
最初は数値がないので、三項演算子を使って一つ前の値が数字でなければ1を入れるというロジックにしています。

コード.gs
    const doPost = (e) => {

        //値の受取り
        const name = e.parameter.name ? e.parameter.name : "";
        const email = e.parameter.email ? e.parameter.email : "";
        const body = e.parameter.body ? e.parameter.body : "";

        //エラー処理
        const email_exp = /^[a-z0-9.]+@[a-z0-9.]+\.[a-z]+$/;
        const body_exp = /^.{1,10}$/;
        
+       //id判定
+       const num = /^[0-9]+$/;
      
        //問題があればエラーを返す(なければ処理を継続)
        if(name == ""|| !email_exp.test(email) || !body_exp.test(body)){
          return ContentService.createTextOutput(JSON.stringify({ message: "validation error!" }));
        }

        //スプレッドシートの準備
        const ss = SpreadsheetApp.getActiveSpreadsheet();
        const sheet = ss.getSheetByName("シート1");

        //row
+       const lastCell = sheet.getRange(sheet.getLastRow(), 1)
+       const value = lastCell.getValue()
+       id = num.test(value) ?  value+1 : 1;

        //シートの一番下の行に追加
-       sheet.appendRow([name, email, body, new Date()]);
+       sheet.appendRow([id,name, email, body, new Date()]);

        //応答
        return ContentService.createTextOutput(JSON.stringify({ message: "success!" }));
    }
コピペ用
const lastCell = sheet.getRange(sheet.getLastRow(), 1)
const value = lastCell.getValue()
id = num.test(value) ?  value+1 : 1;
2
3
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
2
3