이 문서에서는 Google Docs API에서 표를 사용하는 방법을 설명합니다.
Docs API를 사용하면 표 콘텐츠를 수정할 수 있습니다. 수행할 수 있는 작업은 다음과 같습니다.
- 행, 열 또는 전체 표를 삽입하고 삭제합니다.
- 표 셀에 콘텐츠를 삽입합니다.
- 표 셀에서 콘텐츠를 읽습니다.
- 열 속성과 행 스타일을 수정합니다.
Google Docs의 표는 문서에서 StructuralElement 유형으로 표시됩니다. 각 Table에는 TableRow 객체 목록이 포함되며, 각 행에는 TableCell 객체 목록이 포함됩니다. 모든 구조적 요소와 마찬가지로 표에는 문서에서 표의 위치를 나타내는 시작 및 종료 색인이 있습니다. 표 속성에는 열 너비, 패딩 등 다양한 스타일 요소가 포함됩니다.
테이블 예시
다음 JSON 프래그먼트는 세부정보가 대부분 삭제된 2x2 테이블을 보여줍니다.
"table": {
"columns": 2,
"rows": 2,
"tableRows": [
{ "tableCells": [
{
"content": [ { "paragraph": { ... }, } ],
},
{
"content": [ { "paragraph": { ... }, } ],
}
],
},
{
"tableCells": [
{
"content": [ { "paragraph": { ... }, } ],
},
{
"content": [ { "paragraph": { ... }, } ],
}
],
}
]
}
다음 표는 표가 색인 S에서 시작하고 모든 셀이 비어 있다고 가정할 때 (각각 길이가 1인 단일 줄바꿈 문자 \n만 포함) 2x2 표의 각 구조적 요소에 대한 색인 오프셋을 보여줍니다.
| 요소 | 경로 | 시작 색인 | 끝 색인 |
|---|---|---|---|
| 표 | / |
S |
S + 12 |
| TableRow 0 | /rows[0] |
S + 1 |
S + 6 |
| TableCell (0,0) | /rows[0]/cells[0] |
S + 2 |
S + 4 |
| 단락 | /rows[0]/cells[0]/p[0] |
S + 3 |
S + 4 |
| TableCell (0,1) | /rows[0]/cells[1] |
S + 4 |
S + 6 |
| 단락 | /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 |
| 단락 | /rows[1]/cells[0]/p[0] |
S + 8 |
S + 9 |
| TableCell (1,1) | /rows[1]/cells[1] |
S + 9 |
S + 11 |
| 단락 | /rows[1]/cells[1]/p[0] |
S + 10 |
S + 11 |
표 삽입 및 삭제
문서에 표를 추가하려면 InsertTableRequest를 사용합니다.
표를 삽입할 때는 다음을 지정해야 합니다.
- 표의 행과 열 측정기준입니다.
- 표를 삽입할 위치입니다. 세그먼트 (예: 본문, 헤더, 바닥글) 내의 색인일 수도 있고 세그먼트의 끝일 수도 있습니다. 둘 중 하나에는 지정된 탭의 ID가 포함되어야 합니다.
본문 끝에 표를 삽입하려면 EndOfSegmentLocation 객체를 지정하고 segmentId을 비워 둡니다.
표를 삭제하는 명시적 메서드는 없습니다. 문서에서 표를 삭제하려면 다른 콘텐츠와 마찬가지로 처리합니다. DeleteContentRangeRequest를 사용하여 표 전체를 포함하는 range를 지정합니다.
다음 코드 샘플은 빈 문서 끝에 3x3 표를 삽입하는 방법을 보여줍니다.
자바
// 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()
다음 코드 샘플은 시작 및 종료 색인을 지정하여 테이블을 삭제하는 방법을 보여줍니다. 이 샘플에서는 문서 콘텐츠에서 이러한 색인을 가져오는 방법을 보여줍니다.
자바
// 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()
행 삽입 및 삭제
문서에 이미 표가 포함되어 있는 경우 Docs API를 사용해 표 행을 삽입하고 삭제할 수 있습니다. InsertTableRowRequest을 사용하여 지정된 표 셀 앞이나 뒤에 행을 삽입하고 DeleteTableRowRequest을 사용하여 지정된 셀 위치에 걸쳐 있는 행을 삭제합니다.
다음 코드 샘플은 기존 테이블의 첫 번째 셀에 텍스트를 삽입하고 테이블 행을 추가하는 방법을 보여줍니다.
자바
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()
열 삽입 및 삭제
기존 테이블에 열을 삽입하려면 InsertTableColumnRequest을 사용합니다.
다음을 지정해야 합니다.
- 새 열을 삽입할 셀입니다.
- 새 열을 삽입할 쪽 (왼쪽 또는 오른쪽)입니다.
다음 코드 샘플은 앞에서 본 예시 2x2 표에 열을 삽입하는 방법을 보여줍니다.
자바
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()
열을 삭제하려면 DeleteTableColumnRequest을 사용합니다.
열을 삽입할 때와 마찬가지로 대상 열 내의 셀 위치를 지정해야 합니다.
표 셀에서 콘텐츠 읽기
표 셀에는 StructuralElement 객체 목록이 포함됩니다. 이러한 각 구조 요소는 텍스트가 포함된 단락이거나 다른 유형의 구조(다른 표 포함)일 수 있습니다. 표 콘텐츠를 읽으려면 Docs API로 문서에서 텍스트 추출 코드 샘플에 표시된 대로 각 요소를 재귀적으로 검사하면 됩니다.
표 셀에 콘텐츠 삽입
표 셀에 쓰려면 업데이트할 셀의 location로 설정된 InsertTextRequest를 사용합니다. 업데이트된 텍스트를 고려하여 표 색인이 조정됩니다. DeleteContentRangeRequest를 사용하여 셀 텍스트를 삭제하는 경우도 마찬가지입니다.
다음 코드 샘플은 테이블 셀에 쓰는 방법을 보여줍니다.
자바
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()
열 속성 수정
UpdateTableColumnPropertiesRequest을 사용하면 테이블에 있는 하나 이상의 열의 속성을 수정할 수 있습니다.
TableColumnProperties 객체와 함께 테이블의 시작 인덱스를 제공해야 합니다. 선택한 열만 수정하려면 요청에 열 번호 목록을 포함하세요. 표의 모든 열을 수정하려면 빈 목록을 제공하세요.
다음 코드 샘플은 테이블의 열 너비를 업데이트하여 모든 열을 너비 100pt로 설정한 다음 첫 번째 열의 너비를 200pt로 설정하는 방법을 보여줍니다.
자바
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()
행 스타일 수정
UpdateTableRowStyleRequest를 사용하면 테이블에서 하나 이상의 행 스타일을 수정할 수 있습니다.
TableRowStyle 객체와 함께 테이블의 시작 인덱스를 제공해야 합니다. 선택한 행만 수정하려면 요청에 행 번호 목록을 포함하세요. 표의 모든 행을 수정하려면 빈 목록을 제공하세요.
다음 코드 샘플은 표에서 세 번째 행의 최소 높이를 설정하는 방법을 보여줍니다.
자바
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()