You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Apps Script中仅表格标题无法水平居中的问题

问题:Google Apps Script中表格应用样式后水平居中不生效

我设置了以下样式:

var titleStyle = {};
titleStyle[DocumentApp.Attribute.FONT_FAMILY] = 'Calibri';
titleStyle[DocumentApp.Attribute.FONT_SIZE] = 20;
titleStyle[DocumentApp.Attribute.BOLD] = true;
titleStyle[DocumentApp.Attribute.UNDERLINE] = true;
titleStyle[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.CENTER;

var sectionStyle = {};
sectionStyle[DocumentApp.Attribute.FONT_FAMILY] = 'Calibri';
sectionStyle[DocumentApp.Attribute.FONT_SIZE] = 18;
sectionStyle[DocumentApp.Attribute.BOLD] = true;
sectionStyle[DocumentApp.Attribute.UNDERLINE] = true;
sectionStyle[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.CENTER;

用这段代码添加标题并应用样式,水平居中可以成功生效:

var docTitle = noteBody.appendParagraph(title);
docTitle.setAttributes(titleStyle);

但用这段代码添加章节标题表格并应用样式时,字体大小、加粗、下划线等样式都生效,唯独水平居中不生效:

var nextHeader = noteBody.appendTable(headerTable);
nextHeader.setAttributes(sectionStyle);

原因分析

Google Apps Script里,Table对象的setAttributes()方法不会自动将HORIZONTAL_ALIGNMENT属性应用到单元格内的文本上。段落的对齐是直接作用于自身元素,而表格的样式层级分为表格整体对齐和单元格内容对齐,你当前的代码只给表格本身设置了属性,没有覆盖单元格内文本的对齐规则。

解决方法

需要单独遍历表格的单元格,给单元格内的文本段落设置水平对齐属性。修改代码如下:

var nextHeader = noteBody.appendTable(headerTable);
nextHeader.setAttributes(sectionStyle);
nextHeader.setBorderWidth(0);

// 遍历单元格,设置内容水平居中
var rows = nextHeader.getRows();
for (var r = 0; r < rows.length; r++) {
  var cells = rows[r].getCells();
  for (var c = 0; c < cells.length; c++) {
    var paragraph = cells[c].getChild(0).asParagraph();
    paragraph.setAlignment(DocumentApp.HorizontalAlignment.CENTER);
  }
}

另外,你代码中重复调用了nextHeader.setAttributes(sectionStyle);,可以删除其中一个,避免冗余操作。

内容的提问来源于stack exchange,提问作者Raffi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 19:03:13