使用資料表

本文說明如何使用 Google 文件 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": { ... }, } ],
                }
            ],
        }
    ]
}

下表顯示 2x2 表格中每個結構化元素的索引偏移,假設表格從索引 S 開始,且所有儲存格都是空白 (每個儲存格只包含一個換行字元 \n,長度 = 1):

元素 路徑 起始索引 結束索引
資料表 / 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 物件清單。每個結構元素都可以是含有文字的段落,或是其他類型的結構,甚至是另一個表格。如要讀取表格內容,您可以遞迴檢查每個元素,如「使用 Google 文件 API 從文件中擷取文字」程式碼範例所示。

在表格儲存格中插入內容

如要寫入資料表儲存格,請使用 InsertTextRequest 設為要更新的儲存格 location。表格索引會根據更新後的文字進行調整。使用 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 可讓您修改表格中一或多個資料欄的屬性。

您必須提供資料表的起始索引,以及 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 可讓您修改資料表中一或多個資料列的樣式。

您必須提供資料表的起始索引,以及 TableRowStyle 物件。如要只修改所選列,請在要求中加入列號清單。如要修改資料表中的所有資料列,請提供空白清單。

下列程式碼範例顯示如何在表格中設定第三列的最小高度:

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()