为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕桂英3389331 2022-06-05 16:22:04
我有一个带有动态字段标记的 Google Doc,例如%Name% - %Date of Birth%,它从 A 列和 B 列中的谷歌表中获取值:工作表截图正如您所看到的,前 2 列中的值是相同的,因此我在 google 文档中的“%”标签没有问题,因为它采用相同的值。问题在于其他列(C,D,E ...),其中谷歌表上的值是变量。如何在 Google 文档中应用一个标签,该标签动态地获取这些带有变量值的整个列的值?预期结果:此外,如何在脚本中设置具有固定值的列,例如。(黄色)和具有变量值的列,例如。(穿蓝色衣服)?而且,无论如何,如果我过滤电子表格,脚本就不起作用,为什么?
查看完整描述

1 回答

?
青春有我

TA贡献1784条经验 获得超8个赞

  • 您想从电子表格中检索值并放入模板文档。

  • 在您的电子表格中,“A”和“B”列的所有值对于所有行(如john和)都是相同的25/05/1998

  • 您希望通过将占位符替换为电子表格中的值来创建一个 Google 文档。

    • 占位符由 括起来%

  • 您想使用 Google Apps 脚本实现此目的。

我可以像上面那样理解。如果我的理解是正确的,这个答案怎么样?请认为这只是几个可能的答案之一。

流动:

该示例脚本的流程如下。

  1. 从电子表格中检索值。

  2. 创建一个用于放入 Google 文档的对象。

  3. 复制模板 Google 文档。

  4. 使用对象将标题值放入复制的 Document 中。

    • 在这种情况下,占位符将替换为检索到的值。

  5. 使用对象放置表值。

    • 在这种情况下,将检索到的值直接放入模板 Document 中的表中。

示例脚本:

在运行脚本之前,请先设置templateGoogleDocumentID.

function myFunction() {

  var templateGoogleDocumentID = "###";  // Please set the template Google Document ID.


  // 1. Retrieve values from Spreadsheet.

  var activeSheet = SpreadsheetApp.getActiveSheet();

  var values = activeSheet.getDataRange().getValues();


  // 2. Create an object for putting to Google Document.

  var object = {headers: {}, table: {}};

  var headerRow = values.shift();

  object.headers[headerRow[0]] = values[0][0];

  object.headers[headerRow[1]] = Utilities.formatDate(values[0][1], Session.getScriptTimeZone(), "yyyy/MM/dd");

  object.table = values.map(r => r.splice(2, 5));


  // 3. Copy a template Google Document.

  var copiedTemplateDoc = DriveApp.getFileById(templateGoogleDocumentID).makeCopy();

  var docId = copiedTemplateDoc.getId();


  // 4. Put the header values to the copied Document using the object.

  var doc = DocumentApp.openById(docId);

  var body = doc.getBody();

  Object.keys(object.headers).forEach(h => body.replaceText(`%${h.toLowerCase()}%`, object.headers[h]));


  // 5. Put the table values using the object.

  // If the table rows of Google Document are less than that of Spreadsheet, the rows are added.

  var table = body.getTables()[0];

  var r = object.table.length - table.getNumRows();

  if (r > 0) {

    for (var i = 0; i < r; i++) {

      var tr = table.appendTableRow();

      for (var j = 0; j < 3; j++) {

        tr.appendTableCell();

      }

    }

  }

  object.table.forEach((row, i) => (row.forEach((col, j) => (table.getCell(i, j).setText(col)))));

  doc.saveAndClose();


  // If you want to export the Google Document as PDF file, please use the following script.

  // var newFile = DriveApp.createFile(doc.getBlob());

}

笔记:

在此修改后的脚本中,请在脚本编辑器中启用 V8。


查看完整回答
反对 回复 2022-06-05
  • 1 回答
  • 0 关注
  • 79 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信