Work with tables

This document explains how to work with tables in Google Docs API.

The Docs API lets you edit table contents. The operations you can perform include the following:

  • Insert and delete rows, columns, or entire tables.
  • Insert content into table cells.
  • Read content from table cells.
  • Modify column properties and the style of rows.

Tables in Google Docs are represented as a type of StructuralElement in the document. Each Table contains a list of TableRow objects where each row contains a list of TableCell objects. As with all structural elements, the table has start and end indexes, indicating the table's position in a document. Table properties include many style elements such as column widths and padding.

Example table

The following JSON fragment shows a 2x2 table with most of the detail removed:

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

The following table shows the index offsets for each structural element in a 2x2 table, assuming the table starts at index S and all cells are empty (each containing only a single newline character \n with a length = 1):

Element Path Start index End index
Table / 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

Insert and delete tables

To add a table to a document, use the InsertTableRequest. You must specify the following when inserting a table:

  • The table dimensions in rows and columns.
  • The location to insert the table: this can be an index within a segment (such as a body, header, or footer), or it can be the end of a segment. Either one should include the ID of the specified tab.

To insert a table at the end of the body, specify the EndOfSegmentLocation object, and leave the segmentId empty.

There is no explicit method for deleting tables. To delete a table from a document, treat it as you would any other content: use the DeleteContentRangeRequest, specifying a range that covers the entire table.

The following code sample shows how to insert a 3x3 table at the end of an empty document:

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

The following code sample shows how to delete a table by specifying its start and end indexes. This sample demonstrates how to retrieve these indexes from the document content.

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

Insert and delete rows

If your document already contains a table, the Docs API lets you insert and delete table rows. Use the InsertTableRowRequest to insert rows before or after a specified table cell and the DeleteTableRowRequest to remove a row that spans the specified cell location.

The following code sample shows how to insert text into the first cell of an existing table and add a table row:

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

Insert and delete columns

To insert a column into an existing table, use the InsertTableColumnRequest. You must specify the following:

  • A cell next to which you want a new column inserted.
  • Which side (left or right) to insert the new column.

The following code sample shows how to insert a column into the example 2x2 table shown earlier:

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

To delete a column, use the DeleteTableColumnRequest. You must specify the cell location within a target column as shown previously for inserting a column.

Read content from table cells

A table cell contains a list of StructuralElement objects. Each of these structural elements can be a paragraph with text or another type of structure —even another table. To read table contents, you can recursively inspect each element, as shown in the Extract the text from a document with Docs API code sample.

Insert content into table cells

To write to a table cell, use an InsertTextRequest set to the location of the cell you want to update. The table indexes adjust to account for the updated text. The same applies for deleting cell text with the DeleteContentRangeRequest.

The following code sample shows how to write to a table cell:

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

Modifying column properties

The UpdateTableColumnPropertiesRequest lets you modify the properties of one or more of the columns in a table.

You must provide the starting index of the table, along with a TableColumnProperties object. To modify selected columns only, include a list of column numbers in the request. To modify all columns in the table, provide an empty list.

The following code sample shows how to update the column widths of a table, setting all columns to 100 pts wide, then the width of the first column to 200 pts:

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

Modify row styles

The UpdateTableRowStyleRequest lets you modify the style of one or more of the rows in a table.

You must provide the starting index of the table, along with a TableRowStyle object. To modify selected rows only, include a list of row numbers in the request. To modify all rows in the table, provide an empty list.

The following code sample shows how to set the minimum height of row three in a table:

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