【问题标题】:New row not coming with table properties with Apps scriptApps 脚本中的表属性未附带新行
【发布时间】:2026-02-02 09:55:01
【问题描述】:

我尝试在 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-script google-docs google-docs-api


    【解决方案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");
    }
    

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

    希望这会有所帮助!

    【讨论】:

    • 感谢您的评论,但没有成功。 dropbox.com/s/j7ja1lho5gti1xh/ScriptUpdate.jpg?dl=0 正如您在原始附件中所见,我需要为第一个和第二个单元格设置不同的样式。当我添加日志时,lastRowAttributes 也有这些值,{FONT_SIZE=null, ITALIC=null, STRIKETHROUGH=null, FOREGROUND_COLOR=null, MINIMUM_HEIGHT=0, BOLD=null, LINK_URL=null, UNDERLINE=null, FONT_FAMILY=null, Background_COLOR=null }
    • @Mohammedshebin 您能否分享您文档的清理版本,以便我可以针对实际问题进行测试?
    • 您好!我发现你的问题是什么!您已经设置了每个单元格的样式,而不是整个表格。我已经更新了我的答案,以展示如何让它在这两种情况下都能正常工作。