การทำงานกับตาราง

Google Docs API ช่วยให้คุณแก้ไขเนื้อหาตารางได้ การดำเนินการที่คุณทำได้มีดังนี้

  • แทรกและลบแถว คอลัมน์ หรือทั้งตาราง
  • แทรกเนื้อหาลงในเซลล์ตาราง
  • อ่านเนื้อหาจากเซลล์ตาราง
  • แก้ไขพร็อพเพอร์ตี้ของคอลัมน์และรูปแบบของแถว

ตารางใน Google เอกสารจะแสดงเป็นประเภทของ StructuralElement ในเอกสาร ตารางแต่ละรายการมีรายการแถวของตาราง ซึ่งแต่ละแถวมีรายการเซลล์ของตาราง เช่นเดียวกับองค์ประกอบโครงสร้างทั้งหมด ตารางมีดัชนีเริ่มต้นและสิ้นสุด ซึ่งระบุ ตำแหน่งของตารางในเอกสาร ดูข้อมูลเพิ่มเติมเกี่ยวกับการจัดทำดัชนีได้ที่ โครงสร้าง คุณสมบัติของตารางประกอบด้วยองค์ประกอบรูปแบบต่างๆ เช่น ความกว้างของคอลัมน์และ ระยะขอบ

ข้อมูล JSON ต่อไปนี้แสดงตาราง 2x2 แบบง่ายที่นำรายละเอียดส่วนใหญ่ออก แล้ว

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

การแทรกและการลบตาราง

หากต้องการเพิ่มตารางใหม่ลงในเอกสาร ให้ใช้ InsertTableRequest คุณต้องระบุสิ่งต่อไปนี้เมื่อแทรกตาราง

  • มิติข้อมูลตารางในแถวและคอลัมน์
  • ตำแหน่งที่จะแทรกตารางใหม่ ซึ่งอาจเป็นดัชนีภายในกลุ่ม หรืออาจเป็นจุดสิ้นสุดของกลุ่ม ทั้ง 2 อย่างควรมีรหัสของแท็บที่ระบุ

ไม่มีวิธีที่ชัดเจนในการลบตาราง หากต้องการลบตารางออกจากเอกสาร ให้ปฏิบัติต่อตารางเหมือนกับเนื้อหาอื่นๆ โดยใช้ DeleteContentRangeRequest โดยระบุช่วงที่ครอบคลุมทั้งตาราง

ตัวอย่างต่อไปนี้จะแทรกตารางขนาด 3x3 ที่ท้ายเอกสารว่าง

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

ตัวอย่างที่เกี่ยวข้องนี้แสดงวิธีลบตารางที่แทรกไว้ก่อนหน้านี้

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

เนื่องจากคุณลบตารางเป็นเนื้อหาปกติโดยการระบุดัชนีเริ่มต้นและสิ้นสุด คุณจึงต้องรับดัชนีเหล่านี้จากที่ใดที่หนึ่ง ตัวอย่างแสดง วิธีหนึ่งในการดึงดัชนีเหล่านี้จากเนื้อหาของเอกสาร

การแทรกและการลบแถว

หากเอกสารมีตารางอยู่แล้ว Google เอกสาร API จะช่วยให้คุณแทรก และลบแถวในตารางได้ ใช้ InsertTableRowRequest เพื่อแทรกแถวด้านบนหรือด้านล่างของเซลล์ตารางที่ระบุ และใช้ DeleteTableRowRequest เพื่อนําแถวที่ครอบคลุมตําแหน่งเซลล์ที่ระบุออก

ตัวอย่างต่อไปนี้จะแทรกข้อความลงในเซลล์ตารางแรกของตารางและเพิ่ม แถวตาราง

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

การแทรกและการลบคอลัมน์

หากต้องการแทรกคอลัมน์ลงในตารางที่มีอยู่ ให้ใช้ InsertTableColumnRequest คุณต้องระบุข้อมูลต่อไปนี้

  • เซลล์ที่อยู่ข้างเซลล์ที่คุณต้องการแทรกคอลัมน์ใหม่
  • ด้านที่จะแทรกคอลัมน์ใหม่ (ซ้ายหรือขวา)

ตัวอย่างต่อไปนี้แสดงวิธีแทรกคอลัมน์ลงในตาราง 2x2 ที่แสดงก่อนหน้านี้

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

หากต้องการลบคอลัมน์ ให้ใช้ DeleteTableColumnRequest คุณระบุตำแหน่งเซลล์ภายในคอลัมน์เป้าหมายได้เช่นเดียวกับที่แสดงก่อนหน้านี้ สำหรับการแทรกคอลัมน์

การอ่านเนื้อหาจากเซลล์ตาราง

เซลล์ตารางมีรายการองค์ประกอบ โครงสร้าง องค์ประกอบโครงสร้างแต่ละรายการอาจเป็นย่อหน้าที่มีข้อความหรือโครงสร้างประเภทอื่น แม้แต่ตารางอื่น หากต้องการอ่านเนื้อหาของตาราง คุณสามารถ ตรวจสอบแต่ละองค์ประกอบแบบเรียกซ้ำได้ ดังที่แสดงในแยก ข้อความ

การแทรกเนื้อหาลงในเซลล์ตาราง

หากต้องการเขียนไปยังเซลล์ของตาราง ให้ใช้ InsertTextRequest กับดัชนีภายในเซลล์ที่ต้องการอัปเดต ดัชนีของตารางจะปรับให้ สอดคล้องกับข้อความที่อัปเดต การลบข้อความในเซลล์ด้วย DeleteContentRangeRequest ก็เช่นกัน

การแก้ไขพร็อพเพอร์ตี้ของคอลัมน์

UpdateTableColumnPropertiesRequest ช่วยให้คุณแก้ไขพร็อพเพอร์ตี้ของคอลัมน์อย่างน้อย 1 คอลัมน์ในตารางได้

คุณต้องระบุดัชนีเริ่มต้นของตารางพร้อมกับออบเจ็กต์ TableColumnProperties หากต้องการแก้ไขเฉพาะคอลัมน์ที่เลือก ให้ระบุรายการหมายเลขคอลัมน์ในคำขอ หากต้องการแก้ไขคอลัมน์ทั้งหมดในตาราง ให้ระบุรายการว่าง

ตัวอย่างต่อไปนี้จะอัปเดตความกว้างของคอลัมน์ในตาราง โดยตั้งค่าให้ทุกคอลัมน์ มีความกว้าง 100pt จากนั้นตั้งค่าความกว้างของคอลัมน์แรกเป็น 200pt

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

การแก้ไขรูปแบบแถว

UpdateTableRowsStyleRequest ช่วยให้คุณแก้ไขรูปแบบของแถวอย่างน้อย 1 แถวในตารางได้

คุณต้องระบุดัชนีเริ่มต้นของตารางพร้อมกับออบเจ็กต์ TableRowStyle หากต้องการแก้ไขเฉพาะแถวที่เลือก ให้ระบุรายการหมายเลขแถวในคำขอ หากต้องการแก้ไขแถวทั้งหมดในตาราง ให้ระบุรายการว่าง

ตัวอย่างต่อไปนี้กำหนดความสูงขั้นต่ำของแถวที่ 3 ของตาราง

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