新行不随Apps脚本一起提供表属性

问题描述 投票:0回答:1

我试图在Google doc文件内的现有表中添加新行,但是table属性不适用于新行。我能够通过样式保存2个单元格。这是Apps脚本功能

function addRow(fileId)
{
    var body = DocumentApp.openById(fileId).getBody(),
        searchElement = body.findElement(DocumentApp.ElementType.TABLE),
        element = searchElement.getElement(),
        table = element.asTable();

    var cell1Style = table.getRow(0).getCell(0).getAttributes();
    var cell2Style = table.getRow(0).getCell(1).getAttributes();

    cell1Style[DocumentApp.Attribute.BACKGROUND_COLOR] = '#ffffff';
    cell2Style[DocumentApp.Attribute.BACKGROUND_COLOR] = '#ffffff';

    var rowStyle = {};
    rowStyle[DocumentApp.Attribute.BORDER_COLOR] = '#000000';

    var tr = table.appendTableRow();
    tr.setAttributes(rowStyle);
    tr.appendTableCell('My Text:').setAttributes(cell1Style);
    tr.appendTableCell('My value').setAttributes(cell2Style);
}

这里是执行后的文档内容screenshot

您可以看到,即使我已设置边框颜色属性,新行还是会出现在表格外部。请帮助

google-apps-script google-docs google-docs-api
1个回答
1
投票

这是您的操作方式:

function myFunction() {
  var body = DocumentApp.getActiveDocument().getBody();
  var table = body.findElement(DocumentApp.ElementType.TABLE).getElement().asTable();

  var newRow = table.appendTableRow();
  var lastRowAttributes = table.getRow(table.getNumRows()-1).getAttributes()

  newRow.appendTableCell("Text 1").setAttributes(lastRowAttributes);
  newRow.appendTableCell("Text 2").setAttributes(lastRowAttributes);
}

如果这不适用于您,则可以使用:

function myFunction() {
  var body = DocumentApp.getActiveDocument().getBody();
  var table = body.findElement(DocumentApp.ElementType.TABLE).getElement().asTable();

  var lastRow = table.getRow(table.getNumRows()-1);

  var newRow = table.appendTableRow(lastRow.copy());

  newRow.getCell(0).setText("Text 1");
  newRow.getCell(1).setText("Text 2");
}

为了节省时间,我决定将最后一行的样式(在添加之前)用作后面各行的样式。

希望这会有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.