Merge two cell in Docs with google apps script

2019-07-14 05:05发布

Before start, i've searched about this topic on internet but many of the information is old, when was impossible to create a merged cell in Docs using the UI, however now it possible.

Since the google apps script support page said that i need to ask for help in this site.

I want to know if is possible to merge two cell (colspan) with the recent changes in google Docs.

1条回答
Juvenile、少年°
2楼-- · 2019-07-14 05:58

There's a pretty good explanation in the Apps Script Documentation, but the example deals with paragraphs.

Tables in Google Documents are made of TableRow objects filled with TableCell objects. You can think of a table as an array of arrays. In fact, you can use an array of arrays to create a table using the Body.appendTable() method.

TableCells have a merge() method that merges a cell with its preceding sibling cell. The text is joined with a newline.

The code for merging two cells would look something like this:

function mergeCellsExample() {
  //We can use an array of arrays to populate our table.
  var cells = [
    ['First cell', 'Second cell'],
    ['First cell second row', 'Second cell second row']
  ];

  //Creates an example document in your Google Drive Root Folder.
  //It will be titled "Cell merge example"
  var table = DocumentApp.create('Cell merge example').getBody().appendTable(cells);

  // Get the first row in the table.
  var row = table.getRow(0);

  // Get the two cells this row.
  var cell1 = row.getCell(0);
  var cell2 = row.getCell(1);

  // Check the contents of cells 1 and 2
  Logger.log('Cell1 contents: %s', cell1.getText());
  Logger.log('Cell2 contents: %s', cell2.getText());

  // TableCell.merge() merges the current cell into its preceding sibling element.
  var merged = cell2.merge();  
  Logger.log('Merged cell contents: %s', merged.getText());

  // Cell1 and merged are the same cell
  Logger.log('Cell1 == Merged cell: %s', cell1.getText() == merged.getText());
  // Cell2 no longer exists
  Logger.log('Cell2 contents: %s', cell2.getText());
}
查看更多
登录 后发表回答