Home > Mobile >  Google Docs - script to set table row attributes
Google Docs - script to set table row attributes

Time:09-03

How do I set these table row attributes in Google Docs with GAS?

  1. First row: Pin as header row as below:
  2. All rows: Disable 'Allow row to overflow across pages' as shown below:

screenshot of Table properties showing row attributes

CodePudding user response:

Solution:

This can be done with Docs API, which can be used in Apps Script through Advanced Docs Service (which you'll have to enable).

The two requests you are interested in are PinTableHeaderRowsRequest and UpdateTableRowStyleRequest, both of which are part of method documents.batchUpdate.

Both these requests require you to provide the index in the document where the table starts. To get this information, you should call documents.get and find the structural elements in the body that have a table property.

Code sample:

For example, if you wanted to update the first table in your document to pin the first two rows and prevent rows to overflow, you could do the following:

const TABLE_INDEX = 0; // 0-based index of the table you want to update (for example, if you want to update the first table in your document body, this would be 0)
const NUM_PINNED_ROWS = 2; // Number of rows to pin 
const PREVENT_OVERFLOW = true; // Whether to allow row to overflow across pages or not

function updateTable() {
  let currentTableIndex = 0;
  let index;
  let i = 0;
  const documentId = DocumentApp.getActiveDocument().getId();
  const document = Docs.Documents.get(documentId);
  const { content } = document.body;
  while (typeof index === 'undefined' && i < content.length) { // Loop through body content until your table is found
    const element = content[i];
    const { table } = element;
    if (table) { // Check current element is table
      if (TABLE_INDEX === currentTableIndex) {
        index = element.startIndex; // If it's the correct index table, end iteration
      } else {
        currentTableIndex  ;
      }      
    }
    i  ;
  }
  if (typeof index !== 'undefined') { // Check the desired table was found
    const resource = {
      "requests": [
        {
          "pinTableHeaderRows": { // Set pinned rows
            "tableStartLocation": {
              //"segmentId": string, // Uncomment if table is not in doc's body
              "index": index
            },
            "pinnedHeaderRowsCount": NUM_PINNED_ROWS
          }
        },
        {
          "updateTableRowStyle": { // Set row overflow
            "tableStartLocation": {
              //"segmentId": string, // Uncomment if table is not in doc's body
              "index": index
            },
            "tableRowStyle": {
              "preventOverflow": PREVENT_OVERFLOW
            },
            "fields": "preventOverflow"
          }
        }
      ]
    }
    Docs.Documents.batchUpdate(resource, documentId);
  }
}
  • Related