【发布时间】:2022-11-21 08:24:53
【问题描述】:
我想要做的是使用一个 HTML 文件(存在于 Google 工作表的 Apps 脚本中)来填充自动生成的文档的正文。
过程是这样的:
- 工作表中的下拉菜单 > 单击按钮
- Scripts 找到一个没有正文内容的 Doc 模板 > 复制它,重命名它,将它保存到模板所在的同一文件夹中
- 关闭文档。
我不知道如何用 HTML 文件填充 Doc 正文。
这就是我现在所拥有的:(单击工作表中的下拉按钮时调用 htmlTemplate() )
我的 HTML 文件名为 practice-template.HTML
function htmlTemplate() { var sheet = SpreadsheetApp.getActiveSpreadsheet(); var sheetTemplate = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('template') var DOC_ID = '1I5q7BnAdj-KcF10Q6N9TgemMZt0Vkq15ipUfhA_iJTI' // opens Doc Template in Drive // var template = DocumentApp.openById(DOC_ID) // open in Docs when you're saving/creating a new doc var temploc = DriveApp.getFileById(DOC_ID); var dataRange = sheetTemplate.getRange('A1:H1').getValues(); //get data from cells for (i in dataRange) { var rowData = dataRange[i] var dataOne = rowData[0] var dataTwo = rowData[1] var dataThree = rowData[2] } // Get ID of Active sheet var ssloc = DriveApp.getFileById(sheet.getId()); // Get root directory of active workbook var ssfolder = ssloc.getParents().next(); // makes a new google doc based on the template and named appropriately, in the same folder as the template var newcopy = temploc.makeCopy(dataOne,ssfolder); var newcopyurl = newcopy.getUrl(); var doc = DocumentApp.openByUrl(newcopyurl); var docBody = doc.getBody() var htmlBody = HtmlService.createTemplateFromFile('practice-template') var data = { data_one: dataOne, data_two: dataTwo, data_three: dataThree, } htmlBody.data = data; var content = htmlBody.evaluate().getContent(); docBody.replaceText("{{body}}",content) doc.saveAndClose() }当我运行上面的代码时,我在适当的文件夹中得到了一个新的 google Doc,并且文档中填充了 practice-html.html 文件中的 HTML。问题是新的谷歌文档中的文本是 html 语法而不是纯文本。
google Doc 模板文件只有 {{body}} 作为内容。
【问题讨论】:
-
在您的脚本中,
htmlBody.evaluate()返回HtmlOutput对象。如果要使用文本的HTML,请修改var content = htmlBody.evaluate().getContent()。但是,在您的显示脚本中,未声明sheetTemplate。所以,我认为您的脚本在var dataRange = sheetTemplate.getRange('A1:H1').getValues();发生错误。因此,来自I get an error message about docBody.replaceText(content),我担心您可能错误地复制了当前脚本以正确复制当前问题。这个怎么样? -
还有,关于
htmlBody.data = data,在这种情况下,你能提供你的 HTMLpractice-template吗?顺便说一句,您的目标是将 HTML 数据(未呈现的原始 HTML 文本数据)放入 Google 文档中。我的理解正确吗? -
感谢您的回复。我取得了一些进展并编辑了我的问题以反映我在这方面的进展。这是否澄清了一切?
标签: html google-apps-script google-docs