
[英]How do I change the text color within a cell of a Google Docs table in a script?
[英]How can I change the color of a specific border of a Google Docs table by using Google Apps Script?
我在 Google Docs 文档中有几个表格,所有表格都只有一个单元格,并且只有它们的左边框可见。 我通过将彼此的边框宽度设置为 0 来(手动)实现了这一点。我的目标是更改左边框的颜色并保持其他边框不可见(我不在乎怎么做,所以如果有办法实现这个只需为它们设置颜色就可以了,但我还没有找到更改单个边框颜色的方法,所以我不得不更改它们(并将不需要的宽度设置为 0))。
这是一张图片来阐明我的意思(第一个表是表现在的样子,第二个是我想把它改成的样子)
我尝试了以下方法:
tables[i].setBorderColor(myNewColor)
不幸的是,此方法(和 tables[i].setAttributes())仅在左边框宽度为 1px 时有效。 然而,在我的文档中,左边框的宽度为 2.25,因此出于某种原因,代码不会更改边框颜色,因为它没有标准宽度。 有没有办法在不改变宽度的情况下改变左边框颜色,同时保持其他边框几乎不可见?
我相信你的目标如下。
不幸的是,在当前阶段,似乎每个边框都无法由 Google 文档服务 (DocumentApp) 管理。 但是,幸运的是,当使用 Google Docs API 时,这个是可以实现的。 在这个答案中,我想提出一个使用谷歌文档的示例脚本 API。示例脚本如下。
请将以下脚本复制并粘贴到 Google 文档的脚本编辑器中。 在使用此脚本之前, 请在 Advanced Google services 启用 Google Docs API 。
function myFunction() {
const doc = DocumentApp.getActiveDocument();
const documentId = doc.getId();
const body = doc.getBody();
const table = body.getTables()[0]; // Here, the 1st table is used.
const index = body.getChildIndex(table);
const tableStart = Docs.Documents.get(documentId).body.content[index + 1].startIndex;
const borders = ["borderTop", "borderBottom", "borderLeft", "borderRight"];
const resource = {
requests: [
{
updateTableCellStyle: {
tableStartLocation: { index: tableStart },
tableCellStyle: borders.reduce((o, e) => (o[e] = { width: { magnitude: 0, unit: "PT" }, dashStyle: "SOLID", color: { color: { rgbColor: { blue: 0 } } } }, o), {}),
fields: borders.join(",")
}
},
{
updateTableCellStyle: {
tableRange: { tableCellLocation: { tableStartLocation: { index: tableStart }, rowIndex: 0, columnIndex: 0 }, rowSpan: table.getNumRows(), columnSpan: 1 },
tableCellStyle: { borderLeft: { dashStyle: "SOLID", width: { magnitude: 2.25, unit: "PT" }, color: { color: { rgbColor: { red: 1 } } } } },
fields: "borderLeft"
}
}
]
};
Docs.Documents.batchUpdate(resource, documentId);
}
运行此脚本时,Google Document 中的第一个表格仅保留左边框,左边框的颜色更改为红色,如下所示。
问题未解决?试试以下方法:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.