google-apps-script - 使用 Apps 脚本为 GDocs 中的行或表格单元格添加边框
问题描述
我在 GDoc 中有几个表,我想为 GDoc 中最后一个表的新插入行添加边框。下面的代码不会为新创建的行添加边框。
function addBordertoLastTable() {
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var tables = body.getTables();
table = tables[tables.length - 1];
var tr = table.appendTableRow();
var cellStyle = (table.getRow(0).getAttributes())
cellStyle[DocumentApp.Attribute.BOLD] = false;
cellStyle[DocumentApp.Attribute.FOREGROUND_COLOR] = '#343434';
cellStyle[DocumentApp.Attribute.FONT_FAMILY] = 'Arial';
cellStyle[DocumentApp.Attribute.FONT_SIZE] = '8';
cellStyle[DocumentApp.Attribute.BORDER_COLOR] = '#c0c0c0';
cellStyle[DocumentApp.Attribute.FOREGROUND_COLOR] = '#00ff00';
cellStyle[DocumentApp.Attribute.BORDER_WIDTH] = '8';
tr.setAttributes(cellStyle);
tr.appendTableCell('My Text').setAttributes(cellStyle);
tr.appendTableCell('My Text').setAttributes(cellStyle);
tr.appendTableCell('My Text').setAttributes(cellStyle);
}
解决方案
请参考谷歌提供的文档:https ://developers.google.com/apps-script/reference/document/attribute
BORDER_COLOR Enum The border color, for table elements.
BORDER_WIDTH Enum The border width in points, for table elements.
BORDER_WIDTH 和 BORDER_COLOR 是表格属性,而不是单元格属性。
您可以在函数末尾添加以下行以使其工作:
var tableStyle = {};
tableStyle[DocumentApp.Attribute.BORDER_WIDTH] = 8;
tableStyle[DocumentApp.Attribute.BORDER_COLOR] = '#c0c0c0';
table.setAttributes(tableStyle);
如果新手正在阅读本文,最好从 cellStyle 中删除 BORDER_COLOR 和 BORDER_WIDTH 定义,以使代码更易于阅读。