1 回答

TA贡献1784条经验 获得超8个赞
您想从电子表格中检索值并放入模板文档。
在您的电子表格中,“A”和“B”列的所有值对于所有行(如
john
和)都是相同的25/05/1998
。您希望通过将占位符替换为电子表格中的值来创建一个 Google 文档。
占位符由 括起来
%
。您想使用 Google Apps 脚本实现此目的。
我可以像上面那样理解。如果我的理解是正确的,这个答案怎么样?请认为这只是几个可能的答案之一。
流动:
该示例脚本的流程如下。
从电子表格中检索值。
创建一个用于放入 Google 文档的对象。
复制模板 Google 文档。
使用对象将标题值放入复制的 Document 中。
在这种情况下,占位符将替换为检索到的值。
使用对象放置表值。
在这种情况下,将检索到的值直接放入模板 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。
添加回答
举报