Praca z tabelami

Interfejs Google Docs API umożliwia edytowanie zawartości tabel. Możesz wykonywać te działania:

  • Wstawianie i usuwanie wierszy, kolumn lub całych tabel.
  • wstawiać 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 jako typ StructuralElement w dokumencie. Każda tabela zawiera listę wierszy tabeli, a każdy wiersz zawiera listę komórek tabeli. 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. Więcej informacji o indeksowaniu znajdziesz w sekcji struktura. Właściwości tabeli obejmują wiele elementów stylu, takich jak szerokość kolumn i dopełnienie.

Ten fragment kodu JSON przedstawia prostą 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": { ... }, } ],
                }
            ],
        }
    ]
}

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 wstawienia nowej tabeli: może to być indeks w segmencie lub koniec segmentu. Każdy z nich powinien zawierać identyfikator określonej karty.

Nie ma wyraźnej metody usuwania tabel. Aby usunąć tabelę z dokumentu, postępuj tak samo jak w przypadku innych treści: użyj DeleteContentRangeRequest, określając zakres obejmujący całą tabelę.

Poniższy przykład wstawia 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(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()

Tabelę usuwasz jak zwykłą treść – przez podanie indeksów początkowego i końcowego. Musisz więc skądś uzyskać te indeksy. 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 Google Docs API umożliwia wstawianie i usuwanie wierszy tabeli. Użyj InsertTableRowRequest, aby wstawić wiersze powyżej lub poniżej określonej komórki tabeli, oraz DeleteTableRowRequest, aby usunąć wiersz obejmujący określoną komórkę.

W tym przykładzie tekst jest wstawiany do pierwszej komórki tabeli, a następnie dodawany jest 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 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ę.

W przykładzie poniżej pokazujemy, jak wstawić kolumnę do 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(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 DeleteTableColumnRequest. Lokalizację komórki w kolumnie docelowej określa się tak samo jak w przypadku wstawiania kolumny.

Odczytywanie treści z komórek tabeli

Komórka tabeli zawiera listę elementów strukturalnych. Każdy z nich może być akapitem z tekstem lub innym typem struktury, np. inną tabelą. Aby odczytać zawartość tabeli, możesz rekursywnie sprawdzać 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 w odniesieniu do indeksu w komórce, którą chcesz zaktualizować. Indeksy tabeli dostosowują się do zaktualizowanego tekstu. To samo dotyczy usuwania tekstu z komórki za pomocą DeleteContentRangeRequest.

Modyfikowanie właściwości kolumny

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ę.

W tym przykładzie aktualizujemy 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(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 zmodyfikować styl 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ę.

W tym przykładzie ustawiamy minimalną wysokość 3 wiersza 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()