Dokumen ini menjelaskan cara menggunakan tabel di Google Docs API.
Docs API memungkinkan Anda mengedit isi tabel. Operasi yang dapat Anda lakukan meliputi:
- Menyisipkan dan menghapus baris, kolom, atau seluruh tabel.
- Menyisipkan konten ke dalam sel tabel.
- Membaca konten dari sel tabel.
- Ubah properti kolom dan gaya baris.
Tabel di Google Dokumen direpresentasikan sebagai jenis
StructuralElement
dalam dokumen. Setiap
Table berisi daftar
objek TableRow
dengan setiap baris berisi daftar
objek TableCell. Seperti semua elemen struktural, tabel memiliki indeks awal dan akhir, yang menunjukkan
posisi tabel dalam dokumen. Properti tabel mencakup banyak elemen gaya seperti
lebar kolom dan padding.
Tabel contoh
Fragmen JSON berikut menampilkan tabel 2x2 dengan sebagian besar detail dihapus:
"table": {
"columns": 2,
"rows": 2,
"tableRows": [
{ "tableCells": [
{
"content": [ { "paragraph": { ... }, } ],
},
{
"content": [ { "paragraph": { ... }, } ],
}
],
},
{
"tableCells": [
{
"content": [ { "paragraph": { ... }, } ],
},
{
"content": [ { "paragraph": { ... }, } ],
}
],
}
]
}
Tabel berikut menunjukkan offset indeks untuk setiap elemen struktural dalam tabel 2x2, dengan asumsi tabel dimulai pada indeks S dan semua sel kosong (masing-masing hanya berisi satu karakter baris baru \n dengan panjang = 1):
| Elemen | Jalur | Mulai indeks | Indeks akhir |
|---|---|---|---|
| Tabel | / |
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 |
Menyisipkan dan menghapus tabel
Untuk menambahkan tabel ke dokumen, gunakan
InsertTableRequest.
Anda harus menentukan hal berikut saat menyisipkan tabel:
- Dimensi tabel dalam baris dan kolom.
- Lokasi untuk menyisipkan tabel: dapat berupa indeks dalam segmen (seperti isi, header, atau footer), atau dapat berupa akhir segmen. Salah satunya harus mencakup ID tab yang ditentukan.
Untuk menyisipkan tabel di akhir isi, tentukan objek
EndOfSegmentLocation
dan biarkan segmentId kosong.
Tidak ada metode eksplisit untuk menghapus tabel. Untuk menghapus tabel dari
dokumen, perlakukan seperti konten lainnya: gunakan
DeleteContentRangeRequest,
dengan menentukan range yang mencakup seluruh tabel.
Contoh kode berikut menunjukkan cara menyisipkan tabel 3x3 di akhir dokumen kosong:
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()
Contoh kode berikut menunjukkan cara menghapus tabel dengan menentukan indeks awal dan akhir. Contoh ini menunjukkan cara mengambil indeks ini dari konten dokumen.
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()
Menyisipkan dan menghapus baris
Jika dokumen Anda sudah berisi tabel, Docs API memungkinkan Anda menyisipkan dan menghapus baris tabel. Gunakan
InsertTableRowRequest
untuk menyisipkan baris sebelum atau setelah sel tabel yang ditentukan dan
DeleteTableRowRequest
untuk menghapus baris yang mencakup lokasi sel yang ditentukan.
Contoh kode berikut menunjukkan cara menyisipkan teks ke dalam sel pertama tabel yang ada dan menambahkan baris tabel:
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()
Menyisipkan dan menghapus kolom
Untuk menyisipkan kolom ke dalam tabel yang ada, gunakan
InsertTableColumnRequest.
Anda harus menentukan hal berikut:
- Sel di samping tempat Anda ingin menyisipkan kolom baru.
- Sisi mana (kiri atau kanan) untuk menyisipkan kolom baru.
Contoh kode berikut menunjukkan cara menyisipkan kolom ke dalam contoh tabel 2x2 yang ditampilkan sebelumnya:
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()
Untuk menghapus kolom, gunakan
DeleteTableColumnRequest.
Anda harus menentukan lokasi sel dalam kolom target seperti yang ditunjukkan sebelumnya
untuk menyisipkan kolom.
Membaca konten dari sel tabel
Sel tabel berisi daftar objek
StructuralElement. Setiap elemen struktural ini dapat berupa paragraf dengan teks atau
jenis struktur lain —bahkan tabel lain. Untuk membaca isi tabel, Anda
dapat memeriksa setiap elemen secara rekursif, seperti yang ditunjukkan dalam contoh
kode Mengekstrak teks dari dokumen dengan Docs API.
Menyisipkan konten ke dalam sel tabel
Untuk menulis ke sel tabel, gunakan
InsertTextRequest
yang ditetapkan ke location sel yang ingin Anda perbarui. Indeks tabel disesuaikan
untuk memperhitungkan teks yang diperbarui. Hal yang sama berlaku untuk menghapus teks sel dengan
DeleteContentRangeRequest.
Contoh kode berikut menunjukkan cara menulis ke sel tabel:
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()
Mengubah properti kolom
UpdateTableColumnPropertiesRequest
memungkinkan Anda mengubah properti satu atau beberapa kolom dalam tabel.
Anda harus memberikan indeks awal tabel, beserta objek
TableColumnProperties. Untuk mengubah hanya kolom yang dipilih, sertakan daftar nomor kolom dalam
permintaan. Untuk mengubah semua kolom dalam tabel, berikan daftar kosong.
Contoh kode berikut menunjukkan cara memperbarui lebar kolom tabel, dengan menetapkan lebar semua kolom menjadi 100 pt, lalu lebar kolom pertama menjadi 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()
Mengubah gaya baris
UpdateTableRowStyleRequest
memungkinkan Anda mengubah gaya satu atau beberapa baris dalam tabel.
Anda harus memberikan indeks awal tabel, beserta objek
TableRowStyle. Untuk mengubah hanya baris yang dipilih, sertakan daftar nomor baris dalam permintaan. Untuk mengubah semua baris dalam tabel, berikan daftar kosong.
Contoh kode berikut menunjukkan cara menyetel tinggi minimum baris ketiga dalam tabel:
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()