Utilizzo delle tabelle

L'API Google Docs ti consente di modificare i contenuti delle tabelle. Le operazioni che puoi eseguire includono:

  • Inserisci ed elimina righe, colonne o intere tabelle.
  • Inserire contenuti nelle celle della tabella.
  • Legge 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 tabella contiene un elenco di righe di tabella, dove ogni riga contiene un elenco di celle di tabella. Come per tutti gli elementi strutturali, la tabella ha indici di inizio e di fine che indicano la sua posizione nel documento. Per ulteriori informazioni sull'indicizzazione, consulta la struttura. Le proprietà della tabella includono molti elementi di stile, come le larghezze delle colonne e i margini.

Il seguente frammento JSON mostra una semplice 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": { ... }, } ],
                }
            ],
        }
    ]
}

Inserire ed eliminare tabelle

Per aggiungere una nuova 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 nuova tabella: può essere un indice all'interno di un segmento oppure la fine di un segmento. Entrambi devono includere l'ID della scheda specificata.

Non esiste un metodo esplicito per eliminare le tabelle. Per eliminare una tabella da un documento, trattala come faresti con qualsiasi altro contenuto: utilizza DeleteContentRangeRequest, specificando un intervallo che copra l'intera tabella.

L'esempio seguente inserisce una tabella 3 x 3 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(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()

Questo esempio corrispondente mostra come eliminare la tabella inserita in precedenza:

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

Poiché elimini una tabella come contenuti ordinari, specificando gli indici iniziale e finale, devi recuperare questi indici da qualche parte. L'esempio mostra un modo per estrarre questi indici dai contenuti del documento.

Inserire ed eliminare righe

Se il documento contiene già una tabella, l'API Documenti Google ti consente di inserire ed eliminare le righe della tabella. Utilizza InsertTableRowRequest per inserire righe sopra o sotto una cella della tabella specificata e DeleteTableRowRequest per rimuovere una riga che si estende nella posizione della cella specificata.

L'esempio seguente inserisce del testo nella prima cella di una tabella e aggiunge una riga.

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

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 (sinistra o destra) in cui inserire la nuova colonna.

L'esempio seguente mostra come inserire una colonna nella tabella 2x2 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(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()

Per eliminare una colonna, utilizza DeleteTableColumnRequest. Specifica la posizione della cella all'interno di una colonna di destinazione come mostrato in precedenza per l'inserimento di una colonna.

Lettura dei contenuti dalle celle della tabella

Una cella di tabella contiene un elenco di elementi strutturali. ciascuno di questi elementi strutturali può essere un paragrafo con testo o un altro tipo di struttura, anche un'altra tabella. Per leggere i contenuti della tabella, puoi esaminare in modo ricorsivo ogni elemento, come mostrato in Estrai testo.

Inserire contenuti nelle celle della tabella

Per scrivere in una cella di una tabella, utilizza un InsertTextRequest per un indice all'interno della cella da aggiornare. Gli indici della tabella vengono aggiustati in base al testo aggiornato. Lo stesso vale per l'eliminazione del testo della cella con DeleteContentRangeRequest.

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.

L'esempio seguente aggiorna le larghezze delle colonne di una tabella, impostando tutte le colonne su una larghezza di 100 punti e la larghezza della prima colonna su 200 punti:

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

Modificare gli stili di riga

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

L'esempio seguente imposta l'altezza minima della riga 3 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(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()