Làm việc với bảng

API Google Tài liệu cho phép bạn chỉnh sửa nội dung bảng. Các thao tác bạn có thể thực hiện bao gồm:

  • Chèn và xoá hàng, cột hoặc toàn bộ bảng.
  • Chèn nội dung vào các ô trong bảng.
  • Đọc nội dung từ các ô trong bảng.
  • Sửa đổi thuộc tính cột và kiểu của hàng.

Bảng trong Google Tài liệu được biểu thị dưới dạng một loại StructuralElement trong tài liệu. Mỗi bảng chứa một danh sách hàng bảng, trong đó mỗi hàng chứa một danh sách ô bảng. Giống như tất cả các phần tử cấu trúc, bảng có chỉ mục bắt đầu và kết thúc, cho biết vị trí của bảng trong tài liệu. Hãy xem cấu trúc để biết thêm thông tin về việc lập chỉ mục. Thuộc tính bảng bao gồm nhiều phần tử kiểu như chiều rộng cột và khoảng đệm.

Mảnh JSON sau đây cho thấy một bảng 2x2 đơn giản đã xoá hầu hết thông tin chi tiết:

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

Chèn và xoá bảng

Để thêm một bảng mới vào tài liệu, hãy sử dụng InsertTableRequest. Bạn phải chỉ định những thông tin sau khi chèn bảng:

  • Phương diện của bảng theo hàng và cột.
  • Vị trí chèn bảng mới: đây có thể là một chỉ mục trong một phân đoạn hoặc có thể là cuối một phân đoạn. Một trong hai phải bao gồm mã nhận dạng của thẻ được chỉ định.

Không có phương thức rõ ràng để xoá bảng. Để xoá một bảng khỏi tài liệu, hãy coi bảng đó như mọi nội dung khác: sử dụng DeleteContentRangeRequest, chỉ định một phạm vi bao gồm toàn bộ bảng.

Ví dụ sau đây chèn một bảng 3x3 vào cuối tài liệu trống:

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(TAB_ID))
                .setRows(3)
                .setColumns(3)));

BatchUpdateDocumentRequest body =
    new BatchUpdateDocumentRequest().setRequests(requests);
BatchUpdateDocumentResponse response =
    docsService.documents().batchUpdate(DOCUMENT_ID, 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': TAB_ID
        }
    },
}
]

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

Ví dụ tương ứng này cho thấy cách xoá bảng đã chèn trước đó:

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(DOCUMENT_ID).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(DOCUMENT_ID, 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=DOCUMENT_ID, body={'requests': requests}).execute()

Vì bạn xoá bảng dưới dạng nội dung thông thường (bằng cách chỉ định chỉ mục bắt đầu và kết thúc), nên bạn cần lấy các chỉ mục này từ một nơi nào đó. Ví dụ này cho thấy một cách để trích xuất các chỉ mục này từ nội dung tài liệu.

Chèn và xoá hàng

Nếu tài liệu của bạn đã chứa một bảng, thì API Google Tài liệu cho phép bạn chèn và xoá các hàng trong bảng. Sử dụng InsertTableRowRequest để chèn các hàng phía trên hoặc bên dưới một ô bảng đã chỉ định và DeleteTableRowRequest để xoá một hàng trải dài trên vị trí ô đã chỉ định.

Ví dụ sau đây chèn văn bản vào ô bảng đầu tiên của bảng và thêm một hàng bảng.

Java

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

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

Python

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

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

Chèn và xoá cột

Để chèn một cột vào bảng hiện có, hãy sử dụng InsertTableColumnRequest. Bạn phải chỉ định những thông tin sau:

  • Một ô bên cạnh nơi bạn muốn chèn cột mới.
  • Bên (trái hoặc phải) để chèn cột mới.

Ví dụ sau đây cho thấy cách bạn có thể chèn một cột vào bảng 2x2 đã hiển thị trước đó:

Java

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

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

Python

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

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

Để xoá một cột, hãy sử dụng DeleteTableColumnRequest. Bạn chỉ định vị trí ô trong cột mục tiêu giống như đã trình bày trước đó để chèn cột.

Đọc nội dung từ các ô bảng

Một ô trong bảng chứa danh sách các phần tử cấu trúc; mỗi phần tử cấu trúc này có thể là một đoạn văn có văn bản hoặc một loại cấu trúc khác – thậm chí là một bảng khác. Để đọc nội dung bảng, bạn có thể kiểm tra đệ quy từng phần tử, như minh hoạ trong phần Trích xuất văn bản.

Chèn nội dung vào ô bảng

Để ghi vào một ô trong bảng, hãy sử dụng InsertTextRequest cho một chỉ mục trong ô mà bạn muốn cập nhật. Các chỉ mục bảng sẽ điều chỉnh để tính đến văn bản đã cập nhật. Điều này cũng áp dụng cho việc xoá văn bản trong ô bằng DeleteContentRangeRequest.

Sửa đổi thuộc tính cột

UpdateTableColumnPropertiesRequest cho phép bạn sửa đổi thuộc tính của một hoặc nhiều cột trong bảng.

Bạn phải cung cấp chỉ mục bắt đầu của bảng cùng với đối tượng TableColumnProperties. Để chỉ sửa đổi các cột đã chọn, hãy đưa danh sách số cột vào yêu cầu; để sửa đổi tất cả các cột trong bảng, hãy cung cấp danh sách trống.

Ví dụ sau đây cập nhật chiều rộng cột của bảng, đặt tất cả các cột có chiều rộng là 100pt, sau đó đặt chiều rộng của cột đầu tiên là 200pt:

Java

List<Request> requests = new ArrayList<>();
requests.add(
    new Request()
        .setUpdateTableColumnProperties(
            new UpdateTableColumnPropertiesRequest()
                .setTableStartLocation(
                    new Location()
                        .setIndex(2)
                        .setTabId(TAB_ID))
                .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(TAB_ID))
                .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(DOCUMENT_ID, body).execute();

Python

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

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

Sửa đổi kiểu hàng

UpdateTableRowsStyleRequest cho phép bạn sửa đổi kiểu của một hoặc nhiều hàng trong bảng.

Bạn phải cung cấp chỉ mục bắt đầu của bảng cùng với đối tượng TableRowStyle. Để chỉ sửa đổi các hàng đã chọn, hãy đưa danh sách số hàng vào yêu cầu; để sửa đổi tất cả các hàng trong bảng, hãy cung cấp một danh sách trống.

Ví dụ sau đây đặt chiều cao tối thiểu của hàng 3 của bảng:

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(TAB_ID))
                .setRowIndices(rowIndices)
                .setTableRowStyle(
                    new TableRowStyle()
                        .setMinRowHeight(
                            new Dimension().setMagnitude(18d).setUnit("PT")))
                .setFields("*")));

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

Python

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

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