テーブルを操作する

このドキュメントでは、Google Docs API でテーブルを操作する方法について説明します。

Docs API を使用すると、表の内容を編集できます。実行できるオペレーションは次のとおりです。

  • 行、列、表全体を挿入、削除する。
  • 表のセルにコンテンツを挿入します。
  • 表のセルからコンテンツを読み取ります。
  • 列のプロパティと行のスタイルを変更します。

Google ドキュメントの表は、ドキュメント内の StructuralElement 型として表されます。各 Table には TableRow オブジェクトのリストが含まれ、各行には TableCell オブジェクトのリストが含まれます。すべての構造要素と同様に、テーブルには開始インデックスと終了インデックスがあり、ドキュメント内のテーブルの位置を示します。表のプロパティには、列の幅やパディングなど、多くのスタイル要素が含まれています。

表の例

次の JSON フラグメントは、詳細のほとんどが削除された 2x2 のテーブルを示しています。

"table": {
    "columns": 2,
    "rows": 2,
    "tableRows": [
        { "tableCells": [
                {
                    "content": [ { "paragraph": { ...  }, } ],
                },
                {
                    "content": [ { "paragraph": { ... }, } ],
                }
            ],
        },
        {
            "tableCells": [
                {
                    "content": [ { "paragraph": { ... }, } ],
                },
                {
                    "content": [ { "paragraph": { ... }, } ],
                }
            ],
        }
    ]
}

次の表は、テーブルがインデックス S で始まり、すべてのセルが空(それぞれが長さ 1 の改行文字 \n を 1 つだけ含む)であると仮定した場合の、2x2 テーブル内の各構造要素のインデックス オフセットを示しています。

要素 パス 開始インデックス 終了インデックス
テーブル / S S + 12
    TableRow 0 /rows[0] S + 1 S + 6
        TableCell (0,0) /rows[0]/cells[0] S + 2 S + 4
            段落 /rows[0]/cells[0]/p[0] S + 3 S + 4
        TableCell (0,1) /rows[0]/cells[1] S + 4 S + 6
            段落 /rows[0]/cells[1]/p[0] S + 5 S + 6
    TableRow 1 /rows[1] S + 6 S + 11
        TableCell (1,0) /rows[1]/cells[0] S + 7 S + 9
            段落 /rows[1]/cells[0]/p[0] S + 8 S + 9
        TableCell (1,1) /rows[1]/cells[1] S + 9 S + 11
            段落 /rows[1]/cells[1]/p[0] S + 10 S + 11

テーブルを挿入、削除する

ドキュメントにテーブルを追加するには、InsertTableRequest を使用します。テーブルを挿入するときは、次の項目を指定する必要があります。

  • テーブルの行と列のディメンション。
  • 表を挿入する場所: セグメント(本文、ヘッダー、フッターなど)内のインデックス、またはセグメントの末尾を指定できます。どちらにも、指定されたタブの ID が含まれている必要があります。

本文の末尾に表を挿入するには、EndOfSegmentLocation オブジェクトを指定し、segmentId を空のままにします。

テーブルを削除する明示的な方法はありません。ドキュメントからテーブルを削除するには、他のコンテンツと同様に扱います。DeleteContentRangeRequest を使用して、テーブル全体をカバーする range を指定します。

次のコードサンプルは、空のドキュメントの末尾に 3x3 の表を挿入する方法を示しています。

Java

// Insert a table at the end of the body.
// (An empty or unspecified segmentId field indicates the document's body.)

List<Request> requests = new ArrayList<>();
requests.add(
    new Request()
        .setInsertTable(
            new InsertTableRequest()
                .setEndOfSegmentLocation(
                    new EndOfSegmentLocation().setTabId(<var>TAB_ID</var>))
                .setRows(3)
                .setColumns(3)));

BatchUpdateDocumentRequest body =
    new BatchUpdateDocumentRequest().setRequests(requests);
BatchUpdateDocumentResponse response =
    docsService.documents().batchUpdate(<var>DOCUMENT_ID</var>, body).execute();

Python

# Insert a table at the end of the body.
# (An empty or unspecified segmentId field indicates the document's body.)

requests = [{
    'insertTable': {
        'rows': 3,
        'columns': 3,
        'endOfSegmentLocation': {
          'segmentId': '',
          'tabId': <var>TAB_ID</var>
        }
    },
}
]

result = service.documents().batchUpdate(documentId=<var>DOCUMENT_ID</var>, body={'requests': requests}).execute()

次のコードサンプルは、開始インデックスと終了インデックスを指定してテーブルを削除する方法を示しています。このサンプルは、ドキュメント コンテンツからこれらのインデックスを取得する方法を示しています。

Java

// Delete a table that was inserted at the start of the body of the first tab.
// (The table is the second element in the body:
//  documentTab.getBody().getContent().get(2).)

Document document = docsService.documents().get(<var>DOCUMENT_ID</var>).setIncludeTabsContent(true).execute();
String tabId = document.getTabs().get(0).getTabProperties().getTabId();
DocumentTab documentTab = document.getTabs().get(0).getDocumentTab();
StructuralElement table = documentTab.getBody().getContent().get(2);

List<Request> requests = new ArrayList<>();
requests.add(
    new Request()
        .setDeleteContentRange(
            new DeleteContentRangeRequest()
                .setRange(
                    new Range()
                        .setStartIndex(table.getStartIndex())
                        .setEndIndex(table.getEndIndex())
                        .setTabId(tabId))));

BatchUpdateDocumentRequest body =
    new BatchUpdateDocumentRequest().setRequests(requests);
BatchUpdateDocumentResponse response =
    docsService.documents().batchUpdate(<var>DOCUMENT_ID</var>, body).execute();

Python

# Delete a table that was inserted at the start of the body of the first tab.
# (The table is the second element in the body: ['body']['content'][2].)

document = service.documents().get(documentId=DOCUMENT_ID, includeTabsContent=True).execute()
tab_id = document['tabs'][0]['tabProperties']['tabId']
document_tab = document['tabs'][0]['documentTab']
table = document_tab['body']['content'][2]

requests = [{
    'deleteContentRange': {
      'range': {
        'segmentId': '',
        'startIndex': table['startIndex'],
        'endIndex':   table['endIndex'],
        'tabId': tab_id
      }
    },
}
]

result = service.documents().batchUpdate(documentId=<var>DOCUMENT_ID</var>, body={'requests': requests}).execute()

行を挿入、削除する

ドキュメントにすでに表が含まれている場合は、Docs API を使用して表の行を挿入および削除できます。InsertTableRowRequest を使用して、指定したテーブル セルの前または後に列を挿入します。また、DeleteTableRowRequest を使用して、指定したセル位置にまたがる列を削除します。

次のコードサンプルは、既存のテーブルの最初のセルにテキストを挿入し、テーブルの行を追加する方法を示しています。

Java

List<Request> requests = new ArrayList<>();
requests.add(new Request().setInsertText(new InsertTextRequest()
        .setText("Hello")
        .setLocation(new Location().setIndex(5).setTabId(<var>TAB_ID</var>))));
requests.add(new Request().setInsertTableRow(new InsertTableRowRequest()
        .setTableCellLocation(new TableCellLocation()
                .setTableStartLocation(new Location()
                        .setIndex(2).setTabId(<var>TAB_ID</var>))
                .setRowIndex(1)
                .setColumnIndex(1))
        .setInsertBelow(true)));

BatchUpdateDocumentRequest body =
    new BatchUpdateDocumentRequest().setRequests(requests);
BatchUpdateDocumentResponse response = docsService.documents()
        .batchUpdate(<var>DOCUMENT_ID</var>, body).execute();

Python

requests = [{
      'insertText': {
        'location': {
          'index': 5,
          'tabId': <var>TAB_ID</var>
        },
        'text': 'Hello'
    }
  },
  {
    'insertTableRow': {
        'tableCellLocation': {
            'tableStartLocation': {
                'index': 2,
                'tabId': <var>TAB_ID</var>
            },
            'rowIndex': 1,
            'columnIndex': 1
        },
        'insertBelow': 'true'
    }
  }
]

result = service.documents().batchUpdate(documentId=<var>DOCUMENT_ID</var>, body={'requests': requests}).execute()

列を挿入、削除する

既存のテーブルに列を挿入するには、InsertTableColumnRequest を使用します。次の項目を指定する必要があります。

  • 新しい列を挿入する位置の隣にあるセル。
  • 新しい列を挿入する側(左または右)。

次のコードサンプルは、前述の 2x2 のテーブルの例に列を挿入する方法を示しています。

Java

List<Request> requests = new ArrayList<>();
requests.add(
    new Request()
        .setInsertTableColumn(
            new InsertTableColumnRequest()
                .setTableCellLocation(
                    new TableCellLocation()
                        .setTableStartLocation(
                            new Location().setIndex(2).setTabId(<var>TAB_ID</var>))
                        .setRowIndex(0)
                        .setColumnIndex(0))
                .setInsertRight(true)));

BatchUpdateDocumentRequest body =
    new BatchUpdateDocumentRequest().setRequests(requests);
BatchUpdateDocumentResponse response =
    docsService.documents().batchUpdate(<var>DOCUMENT_ID</var>, body).execute();

Python

requests = [{
    'insertTableColumn': {
      'tableCellLocation': {
        'tableStartLocation': {
          'segmentId': '',
          'index': 2,
          'tabId': <var>TAB_ID</var>
        },
        'rowIndex': 0,
        'columnIndex': 0
      },
      'insertRight': True
    },
}
]

result = service.documents().batchUpdate(documentId=<var>DOCUMENT_ID</var>, body={'requests': requests}).execute()

列を削除するには、DeleteTableColumnRequest を使用します。列を挿入する場合と同様に、ターゲット列内のセル位置を指定する必要があります。

テーブルのセルからコンテンツを読み取る

テーブル セルには、StructuralElement オブジェクトのリストが含まれます。これらの構造要素は、テキストを含む段落や、別の構造(別の表など)にすることができます。テーブルの内容を読み取るには、Docs API を使用してドキュメントからテキストを抽出するのコードサンプルに示すように、各要素を再帰的に検査します。

表のセルにコンテンツを挿入する

テーブル セルに書き込むには、更新するセルの location に設定された InsertTextRequest を使用します。更新されたテキストを考慮して、テーブルのインデックスが調整されます。DeleteContentRangeRequest を使用してセルテキストを削除する場合も同様です。

次のコードサンプルは、テーブル セルに書き込む方法を示しています。

Java

List<Request> requests = new ArrayList<>();
requests.add(new Request().setInsertText(new InsertTextRequest()
        .setText("Hello")
        .setLocation(new Location().setIndex(5).setTabId(<var>TAB_ID</var>))));

BatchUpdateDocumentRequest body =
    new BatchUpdateDocumentRequest().setRequests(requests);
BatchUpdateDocumentResponse response = docsService.documents()
        .batchUpdate(<var>DOCUMENT_ID</var>, body).execute();

Python

requests = [{
    'insertText': {
      'location': {
        'index': 5,
        'tabId': <var>TAB_ID</var>
      },
      'text': 'Hello'
    }
}]

result = service.documents().batchUpdate(documentId=<var>DOCUMENT_ID</var>, body={'requests': requests}).execute()

列のプロパティを変更する

UpdateTableColumnPropertiesRequest を使用すると、テーブル内の 1 つ以上の列のプロパティを変更できます。

テーブルの開始インデックスと TableColumnProperties オブジェクトを指定する必要があります。選択した列のみを変更するには、リクエストに列番号のリストを含めます。テーブル内のすべての列を変更するには、空のリストを指定します。

次のコードサンプルは、テーブルの列幅を更新する方法を示しています。すべての列の幅を 100 ポイントに設定し、最初の列の幅を 200 ポイントに設定します。

Java

List<Request> requests = new ArrayList<>();
requests.add(
    new Request()
        .setUpdateTableColumnProperties(
            new UpdateTableColumnPropertiesRequest()
                .setTableStartLocation(
                    new Location()
                        .setIndex(2)
                        .setTabId(<var>TAB_ID</var>))
                .setColumnIndices(null)
                .setTableColumnProperties(
                    new TableColumnProperties()
                        .setWidthType("FIXED_WIDTH")
                        .setWidth(
                            new Dimension().setMagnitude(100d).setUnit("PT")))
                .setFields("*")));

List<Integer> columnIndices = new ArrayList<>();
columnIndices.add(0);
requests.add(
    new Request()
        .setUpdateTableColumnProperties(
            new UpdateTableColumnPropertiesRequest()
                .setTableStartLocation(
                    new Location()
                        .setIndex(2)
                        .setTabId(<var>TAB_ID</var>))
                .setColumnIndices(columnIndices)
                .setTableColumnProperties(
                    new TableColumnProperties()
                        .setWidthType("FIXED_WIDTH")
                        .setWidth(
                            new Dimension().setMagnitude(200d).setUnit("PT")))
                .setFields("*")));

BatchUpdateDocumentRequest body =
    new BatchUpdateDocumentRequest().setRequests(requests);
BatchUpdateDocumentResponse response =
    docsService.documents().batchUpdate(<var>DOCUMENT_ID</var>, body).execute();

Python

requests = [
  {
    'updateTableColumnProperties': {
      'tableStartLocation': {'index': 2, 'tabId': <var>TAB_ID</var>},
      'columnIndices': [],
      'tableColumnProperties': {
        'widthType': 'FIXED_WIDTH',
        'width': {
          'magnitude': 100,
          'unit': 'PT'
        }
      },
      'fields': '*'
    }
  },
  {
    'updateTableColumnProperties': {
      'tableStartLocation': {'index': 2, 'tabId': <var>TAB_ID</var>},
      'columnIndices': [0],
      'tableColumnProperties': {
        'widthType': 'FIXED_WIDTH',
        'width': {
          'magnitude': 200,
          'unit': 'PT'
        }
      },
      'fields': '*'
    }
  }
]

result = service.documents().batchUpdate(documentId=<var>DOCUMENT_ID</var>, body={'requests': requests}).execute()

行のスタイルを変更する

UpdateTableRowStyleRequest を使用すると、テーブル内の 1 つ以上の行のスタイルを変更できます。

テーブルの開始インデックスと TableRowStyle オブジェクトを指定する必要があります。選択した行のみを変更するには、リクエストに行番号のリストを含めます。テーブル内のすべての行を変更するには、空のリストを指定します。

次のコードサンプルは、テーブルの 3 行目の最小の高さを設定する方法を示しています。

Java

List<Integer> rowIndices = new ArrayList<>();
rowIndices.add(3);

List<Request> requests = new ArrayList<>();
requests.add(
    new Request()
        .setUpdateTableRowStyle(
            new UpdateTableRowStyleRequest()
                .setTableStartLocation(
                    new Location()
                        .setIndex(2)
                        .setTabId(<var>TAB_ID</var>))
                .setRowIndices(rowIndices)
                .setTableRowStyle(
                    new TableRowStyle()
                        .setMinRowHeight(
                            new Dimension().setMagnitude(18d).setUnit("PT")))
                .setFields("*")));

BatchUpdateDocumentRequest body =
    new BatchUpdateDocumentRequest().setRequests(requests);
BatchUpdateDocumentResponse response =
    docsService.documents().batchUpdate(<var>DOCUMENT_ID</var>, body).execute();

Python

requests = [{
    'updateTableRowStyle': {
        'tableStartLocation': {'index': 2, 'tabId': <var>TAB_ID</var>},
        'rowIndices': [3],
        'tableRowStyle': {
            'minRowHeight': {
              'magnitude': 18,
              'unit': 'PT'
            }
        },
        'fields': '*'
    },
}
]

result = service.documents().batchUpdate(documentId=<var>DOCUMENT_ID</var>, body={'requests': requests}).execute()