0
2

More than 1 year has passed since last update.

【Google Apps Script】スプレッドシートとの連携まとめ

Last updated at Posted at 2022-03-31

事前準備

スプレッドシートIDの取得

対象のスプレッドシートを開き、URLの以下の部分がシートIDにあたる。
https://docs.google.com/spreadsheets/d/{シートID}/edit#gid=0

スプレッドシートIDとシート名を定数定義しておく。

const GSS_ID = "シートID";
const GSS_SHEET_NAME = "sheetA";

シートの取得

openByIdメソッド、getSheetByNameメソッドを使う。

const book = SpreadsheetApp.openById(GSS_ID);
const sheet = book.getSheetByName(GSS_SHEET_NAME);

書き込み

getRangeメソッド、setValueメソッドを使う。
以下を実行すると、A1セルに「Apple」が書き込まれる。

sheet.getRange("A1").setValue("Apple");

複数行への書き込み

sheet.getRange("A10:B11").setValues([["aaa", "bbb"], ["ccc", "ddd"]]);

最終行への書き込み

appendRowメソッドを使う。
配列で文字列を渡し、複数セルへの書き込みができる。

sheet.appendRow(["Pine", "Apple", "Banana"]);

読み込み

getRangeメソッド、getValueメソッドを使う。

const a1 = sheet.getRange("A1").getValue();
console.log(a1);

複数セルの読み込み

getRangeメソッドで範囲指定し、getValuesメソッドで配列で値を取得できる。

const a1c2 = sheet.getRange("A1:C2").getValues();
console.log(a1c2);

なお、getRangeメソッドは、数値での指定も可能。
A1セルが(1, 1)にあたる。

const a1c2 = sheet.getRange(1, 1, 2, 3).getValues();
console.log(a1c2);
0
2
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
2