עבודה עם טבלאות

במאמר הזה מוסבר איך לעבוד עם טבלאות ב-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": { ... }, } ],
                }
            ],
        }
    ]
}

בטבלה הבאה מוצגים היסטים של אינדקסים לכל רכיב מבני בטבלה בגודל 2x2, בהנחה שהטבלה מתחילה באינדקס S וכל התאים ריקים (כלומר, כל תא מכיל רק תו ירידת שורה יחיד \n באורך 1):

רכיב נתיב אינדקס התחלה אינדקס סיום
טבלה / 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. כשמוסיפים טבלה, צריך לציין את הפרטים הבאים:

  • המאפיינים של הטבלה בשורות ובעמודות.
  • המיקום להוספת הטבלה: יכול להיות אינדקס בתוך קטע (כמו גוף, כותרת או כותרת תחתונה), או סוף קטע. אחד מהם צריך לכלול את המזהה של הכרטיסייה שצוינה.

כדי להוסיף טבלה בסוף הגוף, מציינים את האובייקט EndOfSegmentLocation ומשאירים את segmentId ריק.

אין שיטה מפורשת למחיקת טבלאות. כדי למחוק טבלה ממסמך, צריך להתייחס אליה כמו לכל תוכן אחר: משתמשים ב-DeleteContentRangeRequest ומציינים range שכולל את כל הטבלה.

בדוגמת הקוד הבאה אפשר לראות איך מוסיפים טבלה בגודל 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(<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()

בדוגמת הקוד הבאה מוצגות שתי דרכים למחיקת טבלה: בדוגמה הזו אפשר לראות איך מאחזרים את האינדקסים האלה מתוכן המסמך.

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

הוספה ומחיקה של שורות

אם המסמך כבר מכיל טבלה, אפשר להשתמש ב-Docs API כדי להוסיף ולמחוק שורות בטבלה. משתמשים בתג InsertTableRowRequest כדי להוסיף שורות לפני או אחרי תא מסוים בטבלה, ובתג DeleteTableRowRequest כדי להסיר שורה שחוצה את המיקום של התא שצוין.

בדוגמת הקוד הבאה אפשר לראות איך להוסיף טקסט לתא הראשון בטבלה קיימת ואיך להוסיף שורה לטבלה:

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

הוספה ומחיקה של עמודות

כדי להוסיף עמודה לטבלה קיימת, משתמשים ב-InsertTableColumnRequest. צריך לציין את הפרטים הבאים:

  • תא שלצידו רוצים להוסיף עמודה חדשה.
  • באיזה צד (ימין או שמאל) להוסיף את העמודה החדשה.

בדוגמת הקוד הבאה אפשר לראות איך מוסיפים עמוד לטבלה לדוגמה בגודל 2x2 שמוצגת למעלה:

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

כדי למחוק עמודה, משתמשים בDeleteTableColumnRequest. כדי להוסיף עמודה, צריך לציין את מיקום התא בעמודת היעד, כמו שמוצג למעלה.

קריאת תוכן מתאים בטבלה

תא בטבלה מכיל רשימה של אובייקטים מסוג StructuralElement. כל אחד מהרכיבים האלה יכול להיות פסקה עם טקסט או סוג אחר של מבנה – אפילו טבלה נוספת. כדי לקרוא את תוכן הטבלה, אפשר לבדוק באופן רקורסיבי כל רכיב, כמו בדוגמת הקוד Extract the text from a document with Docs API.

הוספת תוכן לתאים בטבלה

כדי לכתוב לתא בטבלה, משתמשים בתג InsertTextRequest שמוגדר ל-location של התא שרוצים לעדכן. האינדקסים של הטבלה משתנים בהתאם לטקסט המעודכן. אותו עיקרון חל גם על מחיקת טקסט בתא באמצעות DeleteContentRangeRequest.

בדוגמת הקוד הבאה אפשר לראות איך כותבים לתא בטבלה:

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

שינוי מאפייני העמודה

התג UpdateTableColumnPropertiesRequest מאפשר לשנות את המאפיינים של עמודה אחת או יותר בטבלה.

צריך לציין את אינדקס ההתחלה של הטבלה, יחד עם אובייקט TableColumnProperties. כדי לשנות רק עמודות נבחרות, צריך לכלול ברשימה את מספרי העמודות בבקשה. כדי לשנות את כל העמודות בטבלה, צריך לספק רשימה ריקה.

בדוגמת הקוד הבאה מוצג אופן העדכון של רוחב העמודות בטבלה, הגדרת הרוחב של כל העמודות ל-100 נקודות, ואז הגדרת הרוחב של העמודה הראשונה ל-200 נקודות:

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

שינוי סגנונות השורות

התג UpdateTableRowStyleRequest מאפשר לשנות את הסגנון של שורה אחת או יותר בטבלה.

צריך לציין את אינדקס ההתחלה של הטבלה, יחד עם אובייקט TableRowStyle. כדי לשנות רק שורות נבחרות, צריך לכלול ברכיב הבקשה רשימה של מספרי השורות. כדי לשנות את כל השורות בטבלה, צריך לספק רשימה ריקה.

בדוגמת הקוד הבאה אפשר לראות איך מגדירים את הגובה המינימלי של השורה השלישית בטבלה:

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