Google Docs API を使用すると、テーブルの内容を編集できます。実行可能な操作は以下のとおりです。
- 行、列、またはテーブル全体を挿入、削除する。
- テーブル セルにコンテンツを挿入する。
- テーブル セルからコンテンツを読み取る。
- 列のプロパティと行のスタイルを変更する。
Google ドキュメントのテーブルは、ドキュメント内の StructuralElement 型として表されます。各 テーブルには、 の テーブル行のリストが含まれており、 各行にはテーブル セルのリストが含まれています。すべての 構造要素と同様に、テーブルには開始インデックスと終了 インデックスがあり、 ドキュメント内のテーブルの位置を示します。インデックスの詳細については、 構造をご覧ください。テーブルのプロパティには、列の幅やパディングなど、多くのスタイル要素が含まれています。
次の JSON フラグメントは、詳細のほとんどが削除された単純な 2x2 のテーブルを示しています。
"table": {
"columns": 2,
"rows": 2,
"tableRows": [
{ "tableCells": [
{
"content": [ { "paragraph": { ... }, } ],
},
{
"content": [ { "paragraph": { ... }, } ],
}
],
},
{
"tableCells": [
{
"content": [ { "paragraph": { ... }, } ],
},
{
"content": [ { "paragraph": { ... }, } ],
}
],
}
]
}
テーブルの挿入と削除
ドキュメントに新しいテーブルを追加するには、 InsertTableRequest を使用します。 テーブルを挿入するときは、次の項目を指定する必要があります。
- 行と列のテーブルのディメンション。
- 新しいテーブルを挿入する場所。セグメント内のインデックスにすることも、セグメントの末尾にすることもできます。どちらの場合も、指定したタブの ID を含める必要があります。
テーブルを削除する明示的なメソッドはありません。ドキュメントからテーブルを削除するには、他のコンテンツと同様に扱います。 DeleteContentRangeRequest を使用して、テーブル全体をカバーする範囲を指定します。
次の例では、空のドキュメントの末尾に 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()[0].getTabProperties().getTabId(); DocumentTab documentTab = document.getTabs()[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()
テーブルは通常のコンテンツとして削除するため(開始インデックスと終了インデックスを指定)、これらのインデックスをどこからか取得する必要があります。この例では、ドキュメント コンテンツからこれらのインデックスを抽出する 1 つの方法を示します。
行の挿入と削除
ドキュメントにテーブルがすでに含まれている場合、Google 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を使用します。 列を挿入する場合と同様に、ターゲット列内のセル位置を指定します。
テーブル セルからコンテンツを読み取る
テーブル セルには 構造 要素のリストが含まれています。 これらの構造要素は、テキストを含む段落や、別のタイプ の構造(別のテーブルなど)にすることができます。テーブルの内容を読み取るには、 テキストの抽出 で示されているように、各要素を再帰的に検査します。
テーブル セルにコンテンツを挿入する
テーブル セルに書き込むには、更新するセル内のインデックスに InsertTextRequest を使用します。テーブルのインデックスは、更新されたテキストに合わせて調整されます。DeleteContentRangeRequest を使用してセルテキストを削除する場合も同様です。
列のプロパティを変更する
UpdateTableColumnPropertiesRequest を使用すると、テーブル内の 1 つ以上の列のプロパティを変更できます。
テーブルの開始インデックスと TableColumnProperties オブジェクトを指定する必要があります。選択した列のみを変更するには、リクエストに列番号のリストを含めます。テーブル内のすべての列を変更するには、空のリストを指定します。
次の例では、テーブルの列幅を更新し、すべての列を 100 pt の幅に設定してから、最初の列の幅を 200 pt に設定します。
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()
行のスタイルを変更する
UpdateTableRowsStyleRequest を使用すると、テーブル内の 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()