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

Google Docs API cho phép bạn chỉnh sửa nội dung bảng. Các thao tác mà 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 trong các ô của 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 trong bảng, trong đó mỗi hàng chứa một danh sách ô trong bảng. Giống như tất cả các phần tử cấu trúc khá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.

Đoạn JSON sau đây cho thấy một bảng 2x2 đơn giản với hầu hết thông tin chi tiết đã bị xoá:

"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 dùng InsertTableRequest. Bạn phải chỉ định những thông tin sau khi chèn bảng:

  • Kích thước 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 phân đoạn hoặc có thể là cuối phân đoạn. Một trong hai tham số này phải có mã nhận dạng của thẻ được chỉ định.

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

Ví dụ sau đây chèn một bảng 3x3 vào cuối một 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á một 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 minh hoạ 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 đã có bảng, thì Google Docs API 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 bên trên hoặc bên dưới một ô bảng được chỉ định và DeleteTableRowRequest để xoá một hàng trải dài vị trí ô được chỉ định.

Ví dụ sau đây chèn văn bản vào ô đầu tiên của bảng và thêm một hàng vào 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 dùng InsertTableColumnRequest. Bạn phải chỉ định những thông tin sau:

  • Một ô mà bạn muốn chèn cột mới vào bên cạnh.
  • Bên nào (trái hay 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 đã trình bày 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 dùng DeleteTableColumnRequest. Bạn chỉ định vị trí ô trong một cột đích giống như đã trình bày trước đó để chèn một cột.

Đọc nội dung trong các ô của 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 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 từng phần tử một cách đệ quy, như minh hoạ trong phần Trích xuất văn bản.

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

Để ghi vào một ô trong bảng, hãy dùng InsertTextRequest cho một chỉ mục trong ô mà bạn muốn cập nhật. Các chỉ mục của bảng sẽ điều chỉnh để tính đến văn bản đã cập nhật. Điều tương tự 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 các 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 một đối tượng TableColumnProperties. Để chỉ sửa đổi các cột đã chọn, hãy thêm một 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 một danh sách trống.

Ví dụ sau đây cập nhật chiều rộng cột của một bảng, đặt tất cả các cột thành chiều rộng 100pt, sau đó đặt chiều rộng của cột đầu tiên thành 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 một đối tượng TableRowStyle. Để chỉ sửa đổi các hàng đã chọn, hãy thêm 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 cho hàng 3 của một 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()