【发布时间】:2023-03-30 22:32:01
【问题描述】:
慢慢学习如何使用工作表和文档上的谷歌应用脚本进行一些基本的编码。
目前正在根据工作表中收集的信息创建动态报告生成器,但在尝试自定义从工作表到文档的表格时遇到了问题。
我正在尝试在文档中对我的表格应用条带(交替行颜色)以使其看起来更专业和干净,我尝试在很多地方寻找,但似乎找不到任何有效或我至少可以找到的东西理解。
创建文件等没有问题,而且非常容易我已经添加了上下文代码。
function reportgenerator() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('SHEETNAME');
//name for new file
var firstname = sheet.getRange(2,1).getValue();
var reportname = firstname+"'s Report";
//creating document
const googleDocTemplate = DriveApp.getFileById('FILEID');
const destinationFolder = DriveApp.getFolderById('FOLDERID');
const copy = googleDocTemplate.makeCopy(reportname,destinationFolder);
const doc = DocumentApp.openById(copy.getId());
const body = doc.getBody();
我感觉我的问题可能源于以下代码部分,我从中提取数据的范围非常动态,表中的行数可能是 20 到 60+,因此使用 getDataRegion。
// data range for table
var tablerange = sheet.getRange(25,9).getDataRegion();
var tablevalues = tablerange.getValues();
// table style
var tablestyle = {};
tablestyle[DocumentApp.Attribute.FONT_FAMILY] = 'Arial';
tablestyle[DocumentApp.Attribute.FONT_SIZE] = 11;
tablestyle[DocumentApp.Attribute.BORDER_COLOR] = '#ffffff';
tablestyle[DocumentApp.Attribute.BACKGROUND_COLOR] = '#cccccc';
// replace text with table
var rgel = body.findText('{{answertable}}');
var element = rgel.getElement();
var childIndex = body.getChildIndex(element.getParent());
body.getChild(childIndex).asText().setText('');
body.insertTable(childIndex,tablevalues).setAttributes(tablestyle).setColumnWidth(2,55);
doc.saveAndClose();
}
我所做的只是为文本的背景着色,这不符合我的要求,如前所述,我希望对整行应用条带,然后每隔一个,我不熟悉如何使用“for”并创建一个循环以某种方式在单元格/行中读取和着色?但是我对使用“for”非常陌生。
也有一个标题,但对样式的处理相同并将其隔离为与其他单元格不同对我来说一直是个问题。
任何帮助都将不胜感激,免得我的头撞到砖墙上了。
【问题讨论】:
-
能否提供您期望的示例输入输出情况?
-
@Cooper 我已经看到这个问题,当我厌倦了将它应用于我的问题时,它似乎没有帮助,我可能不得不再试一次。
-
@Tanaike 这应该让您了解我所追求的输出 - docs.google.com/document/d/…
-
感谢您的回复。根据您的示例输出情况,我提出了一个示例脚本作为答案。你能确认一下吗?如果这不是您期望的结果,我深表歉意。
标签: google-apps-script google-sheets google-docs-api