Praca z tabelami

Interfejs Google Docs API umożliwia edytowanie zawartości tabeli. Dostępne operacje:

  • wstawiać i usuwać wiersze, kolumny lub całe tabele;
  • Wstawianie treści do komórek tabeli.
  • odczytywać zawartość komórek tabeli;
  • Modyfikuj właściwości kolumn i styl wierszy.

Tabele w Dokumentach Google są reprezentowane w dokumencie jako typ StructuralElement. Każda tabela zawiera listę wierszy tabeli, z których każdy zawiera listę komórek tabeli. Podobnie jak wszystkie elementy strukturalne, tabela ma indeksy początku i końca, które wskazują jej położenie w dokumencie. Więcej informacji o indeksowaniu znajdziesz w sekcji struktura. Właściwości tabeli obejmują wiele elementów stylu, takich jak szerokość kolumn i margines.

Ten fragment kodu JSON pokazuje prostą tabelę 2 x 2 z usuniętymi większością szczegółów:

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

Wstawianie i usuwanie tabel

Aby dodać nową tabelę do dokumentu, użyj elementu InsertTableRequest. Podczas wstawiania tabeli musisz podać te informacje:

  • Wymiary tabeli w wierszach i kolumnach.
  • Miejsce wstawiania nowej tabeli: może to być indeks w segmencie lub koniec segmentu. Każdy z nich powinien zawierać identyfikator określonej karty.

Nie ma jednoznacznej metody usuwania tabel. Aby usunąć tabelę z dokumentu, potraktuj ją jak dowolne inne treści: użyj żądania DeleteContentRangeRequest, podając zakres obejmujący całą tabelę.

W tym przykładzie tabela 3 x 3 jest wstawiana na końcu pustego dokumentu:

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

Ten przykład pokazuje, jak usunąć wcześniej wstawioną tabelę:

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

Ponieważ tabelę usuwasz jako zwykłą treść, podając indeksy początkowy i końcowy, musisz je gdzieś uzyskać. Przykład pokazuje jeden ze sposobów wyodrębniania tych indeksów z treści dokumentu.

Wstawianie i usuwanie wierszy

Jeśli dokument zawiera już tabelę, interfejs API Dokumentów Google umożliwia wstawianie i usuwanie wierszy tabeli. Aby wstawić wiersze nad określoną komórką tabeli lub pod nią, użyj żądania InsertTableRowRequest, a aby usunąć wiersz, który obejmuje określoną komórkę, użyj żądania DeleteTableRowRequest.

W tym przykładzie tekst jest wstawiany do pierwszej komórki tabeli i dodaje wiersz tabeli.

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

Wstawianie i usuwanie kolumn

Aby wstawić kolumnę do istniejącej tabeli, użyj żądania InsertTableColumnRequest. Musisz podać te informacje:

  • Komórka, obok której chcesz wstawić nową kolumnę.
  • Po której stronie (po lewej czy po prawej) ma zostać wstawiona nowa kolumna.

Z tego przykładu dowiesz się, jak wstawić kolumnę do wcześniej pokazanej tabeli 2 x 2:

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

Aby usunąć kolumnę, użyj żądania DeleteTableColumnRequest. Lokalizację komórki w kolumnie docelowej określasz tak samo jak w przypadku wstawiania kolumny.

Czytanie zawartości komórek tabeli

Komórka tabeli zawiera listę elementów strukturalnych. Każdy z tych elementów może być akapitem z tekstem lub innym typem struktury, nawet inną tabelą. Aby odczytać zawartość tabeli, możesz sprawdzić rekurencyjnie każdy element, jak pokazano w sekcji Wyodrębnianie tekstu.

Wstawianie treści do komórek tabeli

Aby zapisać dane w komórce tabeli, użyj elementu InsertTextRequest do indeksu w komórce, którą chcesz zaktualizować. Indeksy tabeli są dostosowywane do zaktualizowanego tekstu. To samo dotyczy usuwania tekstu komórki za pomocą DeleteContentRangeRequest.

Modyfikowanie właściwości kolumny

Za pomocą żądania UpdateTableColumnPropertiesRequest możesz modyfikować właściwości co najmniej 1 kolumny w tabeli.

Musisz podać indeks początkowy tabeli oraz obiekt TableColumnProperties. Aby zmodyfikować tylko wybrane kolumny, dołącz do żądania listę numerów kolumn. Aby zmodyfikować wszystkie kolumny w tabeli, podaj pustą listę.

W tym przykładzie zmieniamy szerokość kolumn tabeli, ustawiając ją na 100 punktów, a potem szerokość pierwszej kolumny na 200 punktów:

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

Modyfikowanie stylów wierszy

Za pomocą żądania UpdateTableRowsStyleRequest możesz zmienić styl co najmniej 1 wiersza w tabeli.

Musisz podać indeks początkowy tabeli oraz obiekt TableRowStyle. Aby zmodyfikować tylko wybrane wiersze, dołącz do żądania listę numerów wierszy. Aby zmodyfikować wszystkie wiersze w tabeli, podaj pustą listę.

W tym przykładzie ustawiamy minimalną wysokość wiersza 3 w tabeli:

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