Questo documento spiega come utilizzare le tabelle nell'API Google Docs.
L'API Docs ti consente di modificare i contenuti delle tabelle. Le operazioni che puoi eseguire includono:
- Inserisci ed elimina righe, colonne o intere tabelle.
- Inserisci contenuti nelle celle della tabella.
- Leggere i contenuti delle celle della tabella.
- Modifica le proprietà delle colonne e lo stile delle righe.
Le tabelle in Documenti Google sono rappresentate come un tipo di
StructuralElement
nel documento. Ogni
Table contiene un elenco
di oggetti TableRow
in cui ogni riga contiene un elenco di oggetti
TableCell. Come tutti gli elementi strutturali, la tabella ha indici di inizio e fine, che indicano la posizione della tabella in un documento. Le proprietà della tabella includono molti elementi di stile, come
larghezza e spaziatura interna delle colonne.
Esempio tabella
Il seguente frammento JSON mostra una tabella 2x2 con la maggior parte dei dettagli rimossi:
"table": {
"columns": 2,
"rows": 2,
"tableRows": [
{ "tableCells": [
{
"content": [ { "paragraph": { ... }, } ],
},
{
"content": [ { "paragraph": { ... }, } ],
}
],
},
{
"tableCells": [
{
"content": [ { "paragraph": { ... }, } ],
},
{
"content": [ { "paragraph": { ... }, } ],
}
],
}
]
}
La seguente tabella mostra gli offset degli indici per ogni elemento strutturale in una tabella 2x2, supponendo che la tabella inizi dall'indice S e che tutte le celle siano vuote (ognuna contenente solo un singolo carattere di nuova riga \n con una lunghezza = 1):
| Elemento | Percorso | Indice iniziale | Indice finale |
|---|---|---|---|
| Tabella | / |
S |
S + 12 |
| TableRow 0 | /rows[0] |
S + 1 |
S + 6 |
| TableCell (0,0) | /rows[0]/cells[0] |
S + 2 |
S + 4 |
| Paragrafo | /rows[0]/cells[0]/p[0] |
S + 3 |
S + 4 |
| TableCell (0,1) | /rows[0]/cells[1] |
S + 4 |
S + 6 |
| Paragrafo | /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 |
| Paragrafo | /rows[1]/cells[0]/p[0] |
S + 8 |
S + 9 |
| TableCell (1,1) | /rows[1]/cells[1] |
S + 9 |
S + 11 |
| Paragrafo | /rows[1]/cells[1]/p[0] |
S + 10 |
S + 11 |
Inserire ed eliminare le tabelle
Per aggiungere una tabella a un documento, utilizza
InsertTableRequest.
Quando inserisci una tabella, devi specificare quanto segue:
- Le dimensioni della tabella in righe e colonne.
- La posizione in cui inserire la tabella: può essere un indice all'interno di un segmento (ad esempio un corpo, un'intestazione o un piè di pagina) oppure la fine di un segmento. Uno dei due deve includere l'ID della scheda specificata.
Per inserire una tabella alla fine del corpo, specifica l'oggetto
EndOfSegmentLocation
e lascia segmentId vuoto.
Non esiste un metodo esplicito per eliminare le tabelle. Per eliminare una tabella da un documento, trattala come qualsiasi altro contenuto: utilizza DeleteContentRangeRequest, specificando un range che copra l'intera tabella.
Il seguente esempio di codice mostra come inserire una tabella 3x3 alla fine di un documento vuoto:
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()
Il seguente esempio di codice mostra come eliminare una tabella specificando gli indici iniziale e finale. Questo esempio mostra come recuperare questi indici dai contenuti del documento.
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()
Inserire ed eliminare righe
Se il documento contiene già una tabella, l'API Docs ti consente di
inserire ed eliminare righe della tabella. Utilizza
InsertTableRowRequest
per inserire righe prima o dopo una cella della tabella specificata e
DeleteTableRowRequest
per rimuovere una riga che si estende nella posizione della cella specificata.
Il seguente esempio di codice mostra come inserire testo nella prima cella di una tabella esistente e aggiungere una riga alla tabella:
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()
Inserire ed eliminare colonne
Per inserire una colonna in una tabella esistente, utilizza
InsertTableColumnRequest.
Devi specificare quanto segue:
- Una cella accanto alla quale vuoi inserire una nuova colonna.
- Il lato (sinistro o destro) in cui inserire la nuova colonna.
Il seguente esempio di codice mostra come inserire una colonna nella tabella 2x2 di esempio mostrata in precedenza:
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()
Per eliminare una colonna, utilizza
DeleteTableColumnRequest.
Devi specificare la posizione della cella all'interno di una colonna di destinazione come mostrato in precedenza
per l'inserimento di una colonna.
Leggere i contenuti delle celle della tabella
Una cella della tabella contiene un elenco di oggetti
StructuralElement. Ciascuno di questi elementi strutturali può essere un paragrafo con testo o
un altro tipo di struttura, ad esempio un'altra tabella. Per leggere i contenuti della tabella, puoi ispezionare in modo ricorsivo ogni elemento, come mostrato nel codice campione Estrai il testo da un documento con l'API Docs.
Inserire contenuti nelle celle della tabella
Per scrivere in una cella della tabella, utilizza un
InsertTextRequest
impostato su location della cella da aggiornare. Gli indici della tabella vengono modificati
per tenere conto del testo aggiornato. Lo stesso vale per l'eliminazione del testo della cella con
il
DeleteContentRangeRequest.
Il seguente esempio di codice mostra come scrivere in una cella di una tabella:
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()
Modifica delle proprietà delle colonne
UpdateTableColumnPropertiesRequest
consente di modificare le proprietà di una o più colonne di una tabella.
Devi fornire l'indice iniziale della tabella, insieme a un oggetto TableColumnProperties. Per modificare solo le colonne selezionate, includi un elenco di numeri di colonna nella
richiesta. Per modificare tutte le colonne della tabella, fornisci un elenco vuoto.
Il seguente esempio di codice mostra come aggiornare le larghezze delle colonne di una tabella, impostando tutte le colonne a 100 pt di larghezza, quindi la larghezza della prima colonna a 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()
Modificare gli stili delle righe
UpdateTableRowStyleRequest
ti consente di modificare lo stile di una o più righe di una tabella.
Devi fornire l'indice iniziale della tabella, insieme a un oggetto TableRowStyle. Per modificare solo le righe selezionate, includi un elenco di numeri di riga nella
richiesta. Per modificare tutte le righe della tabella, fornisci un elenco vuoto.
Il seguente esempio di codice mostra come impostare l'altezza minima della terza riga di una tabella:
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()