首页 > 解决方案 > 带有应用程序脚本的表属性未附带新行

问题描述

我尝试在 Google doc 文件中的现有表中添加新行,但表属性未应用于新行。我能够通过样式保存 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);
}

这是执行后的文档内容 截屏

如您所见,即使我设置了边框颜色属性,新行也出现在表格之外。请帮忙

标签: google-apps-scriptgoogle-docsgoogle-docs-api

解决方案


这是您如何执行此操作的:

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");
}

我决定使用最后一行的样式(在追加之前)作为后续行的样式以节省时间。

希望这可以帮助!


推荐阅读