Z tego dokumentu dowiesz się, jak pracować z tabelami w interfejsie Google Docs API.
Interfejs Docs API umożliwia edytowanie zawartości tabel. Możesz wykonywać te działania:
- wstawiać i usuwać wiersze, kolumny lub całe tabele;
- Wstawianie treści do komórek tabeli.
- odczytywać treści z komórek tabeli;
- Modyfikuj właściwości kolumn i styl wierszy.
Tabele w Dokumentach Google są reprezentowane w dokumencie jako typ StructuralElement. Każdy element Table zawiera listę obiektów TableRow, w której każdy wiersz zawiera listę obiektów TableCell. Podobnie jak w przypadku wszystkich elementów strukturalnych tabela ma indeksy początku i końca, które wskazują jej położenie w dokumencie. Właściwości tabeli obejmują wiele elementów stylu, takich jak szerokość kolumn i dopełnienie.
Przykładowa tabela
Poniższy fragment kodu JSON przedstawia tabelę 2x2, z której usunięto większość szczegółów:
"table": {
"columns": 2,
"rows": 2,
"tableRows": [
{ "tableCells": [
{
"content": [ { "paragraph": { ... }, } ],
},
{
"content": [ { "paragraph": { ... }, } ],
}
],
},
{
"tableCells": [
{
"content": [ { "paragraph": { ... }, } ],
},
{
"content": [ { "paragraph": { ... }, } ],
}
],
}
]
}
W tabeli poniżej przedstawiono przesunięcia indeksu dla każdego elementu strukturalnego w tabeli 2x2, przy założeniu, że tabela zaczyna się od indeksu S, a wszystkie komórki są puste (każda zawiera tylko jeden znak nowego wiersza \n o długości 1):
| Element | Ścieżka | Indeks początkowy | Indeks końcowy |
|---|---|---|---|
| Tabela | / |
S |
S + 12 |
| TableRow 0 | /rows[0] |
S + 1 |
S + 6 |
| TableCell (0,0) | /rows[0]/cells[0] |
S + 2 |
S + 4 |
| Paragraph | /rows[0]/cells[0]/p[0] |
S + 3 |
S + 4 |
| TableCell (0,1) | /rows[0]/cells[1] |
S + 4 |
S + 6 |
| Paragraph | /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 |
| Paragraph | /rows[1]/cells[0]/p[0] |
S + 8 |
S + 9 |
| TableCell (1,1) | /rows[1]/cells[1] |
S + 9 |
S + 11 |
| Paragraph | /rows[1]/cells[1]/p[0] |
S + 10 |
S + 11 |
Wstawianie i usuwanie tabel
Aby dodać tabelę do dokumentu, użyj elementu InsertTableRequest.
Podczas wstawiania tabeli musisz podać te informacje:
- Wymiary tabeli w wierszach i kolumnach.
- Miejsce wstawienia tabeli: może to być indeks w segmencie (np. w treści, nagłówku lub stopce) albo koniec segmentu. Każdy z nich powinien zawierać identyfikator określonej karty.
Aby wstawić tabelę na końcu treści, określ obiekt EndOfSegmentLocation i pozostaw segmentId puste.
Nie ma wyraźnej metody usuwania tabel. Aby usunąć tabelę z dokumentu, postępuj tak samo jak w przypadku innych treści: użyj elementu DeleteContentRangeRequest, określając range obejmujący całą tabelę.
Poniższy przykładowy kod pokazuje, jak wstawić tabelę 3x3 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(<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()
Poniższy przykładowy kod pokazuje, jak usunąć tabelę, podając jej indeksy początkowy i końcowy. Ten przykład pokazuje, jak pobrać te indeksy z treści dokumentu.
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()
Wstawianie i usuwanie wierszy
Jeśli dokument zawiera już tabelę, interfejs Docs API umożliwia wstawianie i usuwanie wierszy tabeli. Użyj ikony
InsertTableRowRequest
, aby wstawić wiersze przed lub za określoną komórką tabeli, oraz ikony
DeleteTableRowRequest
, aby usunąć wiersz obejmujący określoną komórkę.
Poniższy przykładowy kod pokazuje, jak wstawić tekst do pierwszej komórki istniejącej tabeli i dodać wiersz tabeli:
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()
Wstawianie i usuwanie kolumn
Aby wstawić kolumnę do istniejącej tabeli, użyj elementu InsertTableColumnRequest.
Musisz podać te informacje:
- Komórka, obok której chcesz wstawić nową kolumnę.
- Po której stronie (lewej czy prawej) wstawić nową kolumnę.
Poniższy przykładowy kod pokazuje, jak wstawić kolumnę do przykładowej tabeli 2x2 pokazanej wcześniej:
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()
Aby usunąć kolumnę, kliknij DeleteTableColumnRequest.
Aby wstawić kolumnę, musisz określić lokalizację komórki w kolumnie docelowej, jak pokazano wcześniej.
Odczytywanie treści z komórek tabeli
Komórka tabeli zawiera listę obiektów StructuralElement. Każdy z tych elementów strukturalnych może być akapitem z tekstem lub innym typem struktury, a nawet inną tabelą. Aby odczytać zawartość tabeli, możesz rekursywnie sprawdzać każdy element, jak pokazano w przykładzie kodu Wyodrębnianie tekstu z dokumentu za pomocą interfejsu Docs API.
Wstawianie treści do komórek tabeli
Aby zapisać dane w komórce tabeli, użyj elementu
InsertTextRequest
ustawionego na location komórki, którą chcesz zaktualizować. Indeksy tabeli dostosowują się do zaktualizowanego tekstu. To samo dotyczy usuwania tekstu z komórki za pomocą klawisza
DeleteContentRangeRequest.
Poniższy przykładowy kod pokazuje, jak zapisywać dane w komórce tabeli:
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()
Modyfikowanie właściwości kolumny
Pole
UpdateTableColumnPropertiesRequest
umożliwia modyfikowanie właściwości co najmniej jednej kolumny w tabeli.
Musisz podać indeks początkowy tabeli wraz z obiektem TableColumnProperties. Aby zmodyfikować tylko wybrane kolumny, w żądaniu podaj listę numerów kolumn. Aby zmodyfikować wszystkie kolumny w tabeli, podaj pustą listę.
Poniższy przykładowy kod pokazuje, jak zaktualizować szerokość kolumn tabeli, ustawiając szerokość wszystkich kolumn na 100 punktów, a następnie 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(<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()
Modyfikowanie stylów wierszy
Element
UpdateTableRowStyleRequest
umożliwia modyfikowanie stylu co najmniej jednego wiersza w tabeli.
Musisz podać indeks początkowy tabeli wraz z obiektem TableRowStyle. Aby zmodyfikować tylko wybrane wiersze, w żądaniu podaj listę numerów wierszy. Aby zmodyfikować wszystkie wiersze w tabeli, podaj pustą listę.
Poniższy przykładowy kod pokazuje, jak ustawić minimalną wysokość trzeciego wiersza 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(<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()