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`](https://developers.google.com/workspace/docs/api/reference/rest/v1/documents#structuralelement)
in the document. Each
[`Table`](https://developers.google.com/workspace/docs/api/reference/rest/v1/documents#table) contains a list
of [`TableRow`](https://developers.google.com/workspace/docs/api/reference/rest/v1/documents#tablerow)
objects where each row contains a list of
[`TableCell`](https://developers.google.com/workspace/docs/api/reference/rest/v1/documents#tablecell)
objects. As with all structural elements, the table has [start and end
indexes](https://developers.google.com/workspace/docs/api/concepts/structure#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`](https://developers.google.com/workspace/docs/api/reference/rest/v1/documents/request#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](https://developers.google.com/workspace/docs/api/concepts/structure#indexes) (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`](https://developers.google.com/workspace/docs/api/reference/rest/v1/documents/request#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`](https://developers.google.com/workspace/docs/api/reference/rest/v1/documents/request#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


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

<br />

### Python


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

<br />

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


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

<br />

### Python


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

<br />

> [!NOTE]
> **Note:** Because the insertion example inserts the table at the beginning of the body segment, the deletion example expects it to be the third element (zero-indexed). The first two elements are the first section break and paragraph, which are always present and cannot be removed.

## Insert and delete rows

If your document already contains a table, the Docs API lets you
insert and delete table rows. Use the
[`InsertTableRowRequest`](https://developers.google.com/workspace/docs/api/reference/rest/v1/documents/request#inserttablerowrequest)
to insert rows before or after a specified table cell and the
[`DeleteTableRowRequest`](https://developers.google.com/workspace/docs/api/reference/rest/v1/documents/request#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


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

<br />

### Python


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

<br />

## Insert and delete columns

To insert a column into an existing table, use the
[`InsertTableColumnRequest`](https://developers.google.com/workspace/docs/api/reference/rest/v1/documents/request#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](https://developers.google.com/workspace/docs/api/how-tos/tables#example-table) shown earlier:

### Java


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

<br />

### Python


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

<br />

To delete a column, use the
[`DeleteTableColumnRequest`](https://developers.google.com/workspace/docs/api/reference/rest/v1/documents/request#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`](https://developers.google.com/workspace/docs/api/reference/rest/v1/documents#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](https://developers.google.com/workspace/docs/api/samples/extract-text) code
sample.

## Insert content into table cells

To write to a table cell, use an
[`InsertTextRequest`](https://developers.google.com/workspace/docs/api/reference/rest/v1/documents/request#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`](https://developers.google.com/workspace/docs/api/reference/rest/v1/documents/request#deletecontentrangerequest).

> [!NOTE]
> **Note:** You cannot insert a table and write to its cells within a single `batchUpdate` request. Because index translation automatically shifts subsequent insertion indexes past the new table, you must first insert the table, retrieve its `startIndex`, and then send a separate `batchUpdate` request using the correct calculated cell coordinate indexes.

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

### Java


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

<br />

### Python


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

<br />

## Modifying column properties

The
[`UpdateTableColumnPropertiesRequest`](https://developers.google.com/workspace/docs/api/reference/rest/v1/documents/request#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`](https://developers.google.com/workspace/docs/api/reference/rest/v1/documents#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


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

<br />

### Python


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

<br />

## Modify row styles

The
[`UpdateTableRowStyleRequest`](https://developers.google.com/workspace/docs/api/reference/rest/v1/documents/request#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`](https://developers.google.com/workspace/docs/api/reference/rest/v1/documents#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


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

<br />

### Python


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

<br />

## Related topics

- [Batch requests](https://developers.google.com/workspace/docs/api/how-tos/batch)
- [Requests and responses](https://developers.google.com/workspace/docs/api/concepts/request-response)