シート操作したい(Sheet

1const book = SpreadsheetApp.getActiveSpreadsheet();
2const sheet = book.getActiveSheet();

Sheetオブジェクトで単一のシートを操作できます。

シートの情報を確認したい

1const id = sheet.getId();
2const name = sheet.getName();
3const sheetName = sheet.getSheetName();
4
5const index = sheet.getIndex();
6const lastRow = sheet.getLastRow();
7const lastCol = sheet.getLastColumn();

行データを追加したい(appendRow

1// データのカラム数と同じ要素の配列を作成
2const data = ["A", "B", "C", "D"];
3// データをシート末尾に追記
4sheet.appendRow(data);

appendRowで既存のシート末尾にデータを追加できます。

 1type Cell = string | number | boolean | Date | null;
 2type Row = Cell[];
 3
 4function appendRow(
 5  sheet: GoogleAppsScript.Spreadsheet.Sheet,
 6  row: Row
 7) {
 8  const width = sheet.getLastColumn();
 9  if (width !== 0 && row.length !== width) {
10    throw new Error("列数が一致していません");
11  }
12
13  sheet.appendRow(row);
14}
15
16const row: Row = ["A", 123, true, new Date(), null];
17appendRow(sheet, row);

スタンドアロンなスクリプトで、複数のシートを扱う場合、列数のチェックを追加したappendRowのラッパーを作成しておくと便利です。

ヒント

openByIdなどでシートを取得する処理は時間がかかります。 ラッパー関数の中で毎回呼び出すのではなく、 あらかじめ取得したシートを引数として渡すとよいです。

 1type Cell = string | number | boolean | Date | null;
 2type Row = Cell[];
 3
 4function appendRows(
 5  sheet: GoogleAppsScript.Spreadsheet.Sheet,
 6  rows: Row[]
 7) {
 8  if (rows.length === 0) return;
 9
10  const width = rows[0].length;
11
12  // すべての行のカラム数をチェック
13  if (!rows.every(row => row.length === width)) {
14    throw new Error("すべての行の列数が一致していません");
15  }
16
17  sheet
18    .getRange(sheet.getLastRow() + 1, 1, rows.length, width.length)
19    .setValues(rows);
20}
21
22const rows: Row[] = [
23  ["A", "B"],
24  [1, 2],
25];
26appendRows(sheet, rows);

appendRowの処理は時間がかかります。 大量のデータを追加する場合は、 2次元配列を作成しsetValuesで書き出すほうがよいです。

カラム番号を取得したい

 1function getHeaders(
 2  sheet: GoogleAppsScript.Spreadsheet.Sheet
 3): Map<string, number> {
 4  const headers = sheet
 5    .getRange(1, 1, 1, sheet.getLastColumn())
 6    .getValues()[0];
 7
 8  const map = new Map<string, number>();
 9
10  headers.forEach((h, i) => {
11    const key = String(h).trim();
12    if (key) {
13      map.set(key, i + 1);
14    }
15  });
16  return map;
17}
18
19function getColumnIndex(
20  headers: Map<string, number>,
21  name: string
22): number {
23  const index = headers.get(name.trim());
24  if (!index) {
25    throw new Error(`Column "${name}" not found`);
26  }
27  return index;
28}
29
30// Usage
31const headers = getHeaders(sheet);
32const nameColIndex = getColumnIndex(headers, "名前");

スプレッドシート操作は、基本的にカラム番号(1はじまり)が前提となっていますが、カラム追加や順番の変更に弱いです。

このサンプルでは、ヘッダー行をMap型(Map<string, number>)に変換することで、カラム名から安全かつ可読性の高い形でカラム番号を取得できるようにしています。 カラム名で操作できるようになるので、 シートのカラム構成の変更にも強くなります。

データの重複を探したい(findDuplicateRows

 1type Cell = string | number | boolean | Date | null;
 2type Row = Cell[];
 3
 4function toKey(v: Cell): string {
 5  if (v instanceof Date) return String(v.getTime());
 6  if (v === null) return "null";
 7  return String(v);
 8}
 9
10function findDuplicateRow(
11  sheet: GoogleAppsScript.Spreadsheet.Sheet,
12  colIndices: number[],
13  values: Cell[],
14  excludeRowIndex?: number
15): number {
16  if (colIndices.length != values.length) {
17    throw new Error("Length doesn't match: colIndices and values")
18  }
19
20  const lastRow = sheet.getLastRow();
21  if (lastRow < 2) return -1;
22
23  const maxCol = Math.max(...colIndices);
24
25  const rows = sheet
26    .getRange(2, 1, lastRow - 1, maxCol)
27    .getValues() as Cell[][];
28
29  for (let i = 0; i < row.length; i++) {
30    const rowIndex = i + 2;
31    if (rowIndex === excludeRowIndex) continue;
32
33    const row = rows[i];
34
35    const isMatch = colIndices.every((col, j) => toKey(row[col - 1] === toKey(values[j]))
36    );
37    if (isMatch) return rowIndex;
38  }
39  return -1
40}

データを削除したい(deleteRow

1// 2行目を削除
2sheet.deleteRow(2);

deleteRowで行番号を指定してデータを削除できます。

データを削除したい(clearContent

1// 範囲を指定して削除
2const range = sheet.getRange("A2:D6");
3range.clearContent();

clearContentで指定したセル範囲のデータを削除できます。

シート名を変更したい(setName

1sheet.setName("変更後のシート名");

setNameでシート名を変更できます。 同じ名前のシートは作れません。

シートを保護したい(protect

1// シート全体を保護
2const protection = sheet.protect()
3
4// セル範囲を保護
5const range = sheet.getRange("A2:D6");
6const protection = range.protect()
7
8// 保護の理由を追加
9protection.setDescription("説明")

protectでシートや選択したセルを保護できます。 setDescriptionで保護の理由を追加できます。

リファレンス