猿问

如何使用谷歌脚本从谷歌表格中提取特定列到谷歌文档?

我有一个带有动态字段标记的 Google Doc,例如%Name% - %Date of Birth%,它从 A 列和 B 列中的谷歌表中获取值:

工作表截图

正如您所看到的,前 2 列中的值是相同的,因此我在 google 文档中的“%”标签没有问题,因为它采用相同的值。
问题在于其他列(C,D,E ...),其中谷歌表上的值是变量。

如何在 Google 文档中应用一个标签,该标签动态地获取这些带有变量值的整个列的值?

http://img1.mukewang.com/629c67cb0001f4d404720292.jpg

预期结果:


http://img3.mukewang.com/629c67d50001c46805140409.jpg

此外,如何在脚本中设置具有固定值的列,例如。(黄色)和具有变量值的列,例如。(穿蓝色衣服)?

而且,无论如何,如果我过滤电子表格,脚本就不起作用,为什么?

http://img1.mukewang.com/629c67e70001cead11650143.jpg

慕桂英3389331
浏览 93回答 1
1回答

青春有我

您想从电子表格中检索值并放入模板文档。在您的电子表格中,“A”和“B”列的所有值对于所有行(如john和)都是相同的25/05/1998。您希望通过将占位符替换为电子表格中的值来创建一个 Google 文档。占位符由 括起来%。您想使用 Google Apps 脚本实现此目的。我可以像上面那样理解。如果我的理解是正确的,这个答案怎么样?请认为这只是几个可能的答案之一。流动:该示例脚本的流程如下。从电子表格中检索值。创建一个用于放入 Google 文档的对象。复制模板 Google 文档。使用对象将标题值放入复制的 Document 中。在这种情况下,占位符将替换为检索到的值。使用对象放置表值。在这种情况下,将检索到的值直接放入模板 Document 中的表中。示例脚本:在运行脚本之前,请先设置templateGoogleDocumentID.function myFunction() {&nbsp; var templateGoogleDocumentID = "###";&nbsp; // Please set the template Google Document ID.&nbsp; // 1. Retrieve values from Spreadsheet.&nbsp; var activeSheet = SpreadsheetApp.getActiveSheet();&nbsp; var values = activeSheet.getDataRange().getValues();&nbsp; // 2. Create an object for putting to Google Document.&nbsp; var object = {headers: {}, table: {}};&nbsp; var headerRow = values.shift();&nbsp; object.headers[headerRow[0]] = values[0][0];&nbsp; object.headers[headerRow[1]] = Utilities.formatDate(values[0][1], Session.getScriptTimeZone(), "yyyy/MM/dd");&nbsp; object.table = values.map(r => r.splice(2, 5));&nbsp; // 3. Copy a template Google Document.&nbsp; var copiedTemplateDoc = DriveApp.getFileById(templateGoogleDocumentID).makeCopy();&nbsp; var docId = copiedTemplateDoc.getId();&nbsp; // 4. Put the header values to the copied Document using the object.&nbsp; var doc = DocumentApp.openById(docId);&nbsp; var body = doc.getBody();&nbsp; Object.keys(object.headers).forEach(h => body.replaceText(`%${h.toLowerCase()}%`, object.headers[h]));&nbsp; // 5. Put the table values using the object.&nbsp; // If the table rows of Google Document are less than that of Spreadsheet, the rows are added.&nbsp; var table = body.getTables()[0];&nbsp; var r = object.table.length - table.getNumRows();&nbsp; if (r > 0) {&nbsp; &nbsp; for (var i = 0; i < r; i++) {&nbsp; &nbsp; &nbsp; var tr = table.appendTableRow();&nbsp; &nbsp; &nbsp; for (var j = 0; j < 3; j++) {&nbsp; &nbsp; &nbsp; &nbsp; tr.appendTableCell();&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; }&nbsp; object.table.forEach((row, i) => (row.forEach((col, j) => (table.getCell(i, j).setText(col)))));&nbsp; doc.saveAndClose();&nbsp; // If you want to export the Google Document as PDF file, please use the following script.&nbsp; // var newFile = DriveApp.createFile(doc.getBlob());}笔记:在此修改后的脚本中,请在脚本编辑器中启用 V8。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答