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

Google Docs API מאפשר לערוך תוכן של טבלה. הפעולות שאתם יכולים לבצע כוללות:

  • להוסיף ולמחוק שורות, עמודות או טבלאות שלמות.
  • הוספת תוכן לתאי הטבלה.
  • קריאת תוכן מתאי הטבלה.
  • שינוי מאפייני עמודות וסגנון השורות.

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

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

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

הוספה ומחיקה של טבלאות

כדי להוסיף טבלה חדשה למסמך, השתמשו באפשרות InsertTableRequest. כשמוסיפים טבלה, צריך לציין את הפרטים הבאים:

  • מאפייני הטבלה בשורות ובעמודות.
  • המיקום שבו יש להוסיף את הטבלה החדשה: אינדקס בתוך פלח או סוף פלח.

אין שיטה מפורשת למחיקת טבלאות. כדי למחוק טבלה ממסמך, יש להתייחס אליה כמו לכל תוכן אחר: משתמשים ב-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())
                .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': ''
          }
      },
  }
  ]

  result = service.documents().batchUpdate(documentId=DOCUMENT_ID, body={'requests': requests}).execute()

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

Java

// Delete a table that was inserted at the start of the body.
// (The table is the second element in the body:
//  document.getBody().getContent().get(2).)

Document document = docsService.documents().get(DOCUMENT_ID).execute();
StructuralElement table = document.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()))));

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.
  # (The table is the second element in the body: ['body']['content'][2].)

  document = service.documents().get(documentId=DOCUMENT_ID).execute()
  table = document['body']['content'][2]

  requests = [{
      'deleteContentRange': {
        'range': {
          'segmentId': '',
          'startIndex': table['startIndex'],
          'endIndex':   table['endIndex']
        }
      },
  }
  ]

  result = service.documents().batchUpdate(documentId=DOCUMENT_ID, body={'requests': requests}).execute()

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

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

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

בדוגמה הבאה מוסיפים טקסט לתא הראשון בטבלה ומוסיפה שורה בטבלה.

Java

List<Request> requests = new ArrayList<>();
requests.add(new Request().setInsertText(new InsertTextRequest()
        .setText("Hello")
        .setLocation(new Location().setIndex(5))));
requests.add(new Request().setInsertTableRow(new InsertTableRowRequest()
        .setTableCellLocation(new TableCellLocation()
                .setTableStartLocation(new Location()
                        .setIndex(2))
                .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
          },
          'text': 'Hello'
      }
    },
    {
      'insertTableRow': {
          'tableCellLocation': {
              'tableStartLocation': {
                      'index': 2
              },
              '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))
                        .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
          },
          'rowIndex': 0,
          'columnIndex': 0
        },
        'insertRight': True
      },
  }
  ]

  result = service.documents().batchUpdate(documentId=DOCUMENT_ID, body={'requests': requests}).execute()

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

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

תא בטבלה מכיל רשימה של רכיבים מבניים. כל אחד מהאלמנטים המבניים האלה יכול להיות פסקה עם טקסט או סוג אחר של מבנה, גם אם מדובר בטבלה אחרת. כדי לקרוא את תוכן הטבלה, אפשר לבדוק באופן חזרתי כל רכיב, כפי שמתואר במאמר חילוץ טקסט.

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

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

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

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

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

הדוגמה הבאה מעדכנת את רוחב העמודות בטבלה, כאשר כל העמודות מוגדרות לרוחב של 100 נקודות ורוחב העמודה הראשונה הוא 200pt:

Java

List<Request> requests = new ArrayList<>();
requests.add(
    new Request()
        .setUpdateTableColumnProperties(
            new UpdateTableColumnPropertiesRequest()
                .setTableStartLocation(new Location().setIndex(2))
                .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))
                .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},
      'columnIndices': [],
      'tableColumnProperties': {
        'widthType': 'FIXED_WIDTH',
        'width': {
          'magnitude': 100,
          'unit': 'PT'
        }
      },
      'fields': '*'
    },
    'updateTableColumnProperties': {
      'tableStartLocation': {'index': 2},
      'columnIndices': [0],
      'tableColumnProperties': {
        'widthType': 'FIXED_WIDTH',
        'width': {
          'magnitude': 200,
          'unit': 'PT'
        }
      },
      'fields': '*'
    },
  }
  ]

  result = service.documents().batchUpdate(documentId=DOCUMENT_ID, body={'requests': requests}).execute()

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

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

עליכם לספק את האינדקס ההתחלתי של הטבלה, יחד עם אובייקט 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))
                .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},
          'rowIndices': [3],
          'tableRowStyle': {
              'minRowHeight': {
                'magnitude': 18,
                'unit': 'PT'
              }
          },
          'fields': '*'
      },
  }
  ]

  result = service.documents().batchUpdate(documentId=DOCUMENT_ID, body={'requests': requests}).execute()