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. Bạn có thể thực hiện các thao tác sau đây:

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

Các 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 các hàng trong bảng, trong đó mỗi hàng chứa một danh sách các ô trong bảng. Tương tự như với mọi thành phần cấu trúc, bảng có chỉ mục bắt đầu và chỉ mục 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, chẳng hạn như chiều rộng và khoảng đệm của cột.

Phân mảnh JSON sau đây hiển thị một bảng 2x2 đơn giản với hầu hết thông tin chi tiết đã được loại bỏ:

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

Chèn và xoá bảng

Để thêm 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:

  • Kích thước của bảng theo hàng và cột.
  • Vị trí cần chèn bảng mới: đây có thể là chỉ mục trong một phân đoạn hoặc có thể là phần cuối của một phân đoạn.

Không có phương pháp rõ ràng nào để xoá bảng. Để xoá bảng khỏi một tài liệu, hãy xem tài liệu đó giống như bất kỳ nội dung nào 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 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())
                .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': ''
          }
      },
  }
  ]

  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.
// (The table is the second element in the body:
//  document.getBody().getContent().get(2).)

Document document = docsService.documents().get(DOCUMENT_ID).execute();
StructuralElement table = document.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()))));

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.
  # (The table is the second element in the body: ['body']['content'][2].)

  document = service.documents().get(documentId=DOCUMENT_ID).execute()
  table = document['body']['content'][2]

  requests = [{
      'deleteContentRange': {
        'range': {
          'segmentId': '',
          'startIndex': table['startIndex'],
          'endIndex':   table['endIndex']
        }
      },
  }
  ]

  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ụ 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 bảng, thì API Google Tài liệu sẽ cho phép bạn chèn và xoá hàng trong bảng. Hãy sử dụng InsertTableRowRequest để chèn các hàng bên trên hoặc bên dưới một ô trong bảng được chỉ định và DeleteTableRowRequest để xoá một hàng trải rộng đến vị trí ô đã chỉ định.

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

Java

List<Request> requests = new ArrayList<>();
requests.add(new Request().setInsertText(new InsertTextRequest()
        .setText("Hello")
        .setLocation(new Location().setIndex(5))));
requests.add(new Request().setInsertTableRow(new InsertTableRowRequest()
        .setTableCellLocation(new TableCellLocation()
                .setTableStartLocation(new Location()
                        .setIndex(2))
                .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
          },
          'text': 'Hello'
      }
    },
    {
      'insertTableRow': {
          'tableCellLocation': {
              'tableStartLocation': {
                      'index': 2
              },
              '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:

  • Ô bên cạnh ô mà bạn muốn chèn cột mới.
  • Bên nào (trái hoặc phải) cần chèn cột mới.

Ví dụ sau cho biết cách bạn có thể chèn một cột vào bảng 2x2 như minh hoạ trước đó:

Java

List<Request> requests = new ArrayList<>();
requests.add(
    new Request()
        .setInsertTableColumn(
            new InsertTableColumnRequest()
                .setTableCellLocation(
                    new TableCellLocation()
                        .setTableStartLocation(
                            new Location().setIndex(2))
                        .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
          },
          'rowIndex': 0,
          'columnIndex': 0
        },
        'insertRight': True
      },
  }
  ]

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

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

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

Ô trong bảng chứa danh sách các thành phần cấu trúc; mỗi thành phần cấu trúc 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 mục lục, 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 các ô của bảng

Để ghi vào một ô trong bảng, hãy sử dụng InsertTextRequest vào 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 để phù hợp với văn bản được 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 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 đố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 một danh sách trống.

Ví dụ sau đây sẽ cập nhật chiều rộng cột của bảng, đặt chiều rộng tất cả các cột thành 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))
                .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))
                .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},
      'columnIndices': [],
      'tableColumnProperties': {
        'widthType': 'FIXED_WIDTH',
        'width': {
          'magnitude': 100,
          'unit': 'PT'
        }
      },
      'fields': '*'
    },
    'updateTableColumnProperties': {
      'tableStartLocation': {'index': 2},
      '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, đư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 trong 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))
                .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},
          'rowIndices': [3],
          'tableRowStyle': {
              'minRowHeight': {
                'magnitude': 18,
                'unit': 'PT'
              }
          },
          'fields': '*'
      },
  }
  ]

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