Tài liệu này giải thích cách xử lý bảng trong Google Tài liệu API.
Docs API 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 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 Table chứa một danh sách các đối tượng TableRow, trong đó mỗi hàng chứa một danh sách các đối tượng TableCell. Giống như mọi phần tử cấu trúc, bảng này 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. 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.
Bảng ví dụ
Đoạn JSON sau đây cho thấy một bảng 2x2 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": { ... }, } ],
}
],
}
]
}
Bảng sau đây cho thấy độ lệch chỉ mục cho từng phần tử cấu trúc trong bảng 2x2, giả sử bảng bắt đầu ở chỉ mục S và tất cả các ô đều trống (mỗi ô chỉ chứa một ký tự dòng mới \n có độ dài = 1):
| Phần tử | Đường dẫn | Chỉ số bắt đầu | Chỉ mục kết thúc |
|---|---|---|---|
| Bảng | / |
S |
S + 12 |
| TableRow 0 | /rows[0] |
S + 1 |
S + 6 |
| TableCell (0,0) | /rows[0]/cells[0] |
S + 2 |
S + 4 |
| Đoạn | /rows[0]/cells[0]/p[0] |
S + 3 |
S + 4 |
| TableCell (0,1) | /rows[0]/cells[1] |
S + 4 |
S + 6 |
| Đoạn | /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 |
| Đoạn | /rows[1]/cells[0]/p[0] |
S + 8 |
S + 9 |
| TableCell (1,1) | /rows[1]/cells[1] |
S + 9 |
S + 11 |
| Đoạn | /rows[1]/cells[1]/p[0] |
S + 10 |
S + 11 |
Chèn và xoá bảng
Để thêm bảng vào tài liệu, hãy dùng biểu tượ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: đây có thể là một chỉ mục trong phân đoạn (chẳng hạn như nội dung, tiêu đề hoặc chân trang) 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.
Để chèn một bảng vào cuối nội dung, hãy chỉ định đối tượng EndOfSegmentLocation và để trống segmentId.
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 range bao gồm toàn bộ bảng.
Mã mẫu sau đây cho biết cách 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(<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()
Mã mẫu sau đây cho biết cách xoá một bảng bằng cách chỉ định chỉ mục bắt đầu và chỉ mục kết thúc của bảng đó. Mẫu này minh hoạ cách truy xuất các chỉ mục này từ nội dung tài liệu.
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()
Chèn và xoá hàng
Nếu tài liệu của bạn đã có bảng, thì Docs API cho phép bạn chèn và xoá các hàng trong bảng. Sử dụng biểu tượng InsertTableRowRequest để chèn các hàng trước hoặc sau một ô bảng được chỉ định và biểu tượng DeleteTableRowRequest để xoá một hàng trải dài vị trí ô được chỉ định.
Mã mẫu sau đây cho biết cách chèn văn bản vào ô đầu tiên của một bảng hiện có 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(<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()
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.
Đoạn mã mẫu sau đây cho thấy cách chèn một cột vào bảng ví dụ 2x2 đã xuất hiện trước đó:
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()
Để xoá một cột, hãy dùng biểu tượng DeleteTableColumnRequest.
Bạn phải chỉ định vị trí ô trong một cột đích 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 đối tượng StructuralElement. 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ư trong mẫu mã Trích xuất văn bản từ tài liệu bằng Docs API.
Chèn nội dung vào các ô trong bảng
Để ghi vào một ô trong bảng, hãy dùng một InsertTextRequest được đặt thành location của ô 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 này cũng áp dụng cho việc xoá văn bản trong ô bằng DeleteContentRangeRequest.
Mã mẫu sau đây cho biết cách ghi vào một ô trong bảng:
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()
Sửa đổi thuộc tính cột
Biểu tượng 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 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.
Mã mẫu sau đây cho thấy cách 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 100 pt, sau đó đặt chiều rộng của cột đầu tiên thành 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()
Sửa đổi kiểu hàng
UpdateTableRowStyleRequest 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.
Mã mẫu sau đây cho biết cách đặt chiều cao tối thiểu của hàng thứ ba trong 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(<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()