这是我的代码,我无法弄清楚为什么replaceText()不起作用。
function createDoc(){
var templateid = "1jM-6Qvy47gQ45u88WfDU_RvfuSTsw27zBP_9MfsUGr8"; // get template file id
var FOLDER_NAME = "Completed Rental Agreements"; // folder name of where to put doc
// get the data from an individual user
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var data = sheet.getRange(2, 1, sheet.getLastRow()-1,sheet.getLastColumn()).getValues();
var lastRow = sheet.getLastRow();
var firstName = sheet.getRange(lastRow, 2, 1,1).getValues();
var lastName = sheet.getRange(lastRow, 3, 1,1).getValues();
var guestEmail = sheet.getRange(lastRow, 7, 1,1).getValues();
var companyEmail = "bearlakeprojectmanagement@yahoo.com";
var companyName = "Bear Lake Project Management";
var username = "jared.hislop.test@gmail.com"; // get their email (from sheet name)
var me = "jared.hislop.test@gmail.com";
//Copy Template
var docid = DocsList.getFileById(templateid).makeCopy("Rental Agreement - "+firstName+""+lastName+"-"+guestEmail).getId();
// var file = DocsList.getFileById(docid).addEditors(me);
// move file to right folder
var file = DocsList.getFileById(docid);
var folder = DocsList.getFolder(FOLDER_NAME);
file.addToFolder(folder);
var doc = DocumentApp.openById(docid);
var body = doc.getActiveSection();
var body_text = doc.addEditor("jared.hislop.test@gmail.com");
// Append Cabin Rules
// doc.appendParagraph("This is a typical paragraph.");
body.replaceText("/^companyEmail$/", "test");
body.replaceText("%companyName%", "test1");
body.replaceText("%todayDate%", "test1");
doc.saveAndClose();
}
我已经尝试过doc.replaceText和body.replaceText以及其他几个选项。
为什么这不起作用?
提前感谢
答案 0 :(得分:4)
考虑一下:
body.replaceText("%companyName%", "test1");
这将查找“companyName”的每个实例,其中包含“%”。在这种情况下,“%”只是一个在一个陌生的地方的标点符号。这是一种用于降低意外替换文档中真实文本的可能性的惯例。
您的模板文档必须具有确切的模式才能使替换工作。 (你的不是......而是你只有“companyName”。将它改为“%companyName%”。)将该规则应用于你想做的任何其他替换。
您可以从一些优化中受益。
...
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
// Next line is hard to maintain - there's a better way.
// var data = sheet.getRange(2, 1, sheet.getLastRow()-1,sheet.getLastColumn()).getValues();
// Read whole spreadsheet, skip headers
var data = sheet.getDataRange().getValues().slice(1);
// Already read in all data, use it instead of reading sheet again.
var firstName = data[data.length-1][2-1]; // (2-1) because array counts from 0
var lastName = data[data.length-1][3-1]; // while spreadsheet columns from 1
var guestEmail = data[data.length-1][7-1]; // Better: put these into variables.
...
在尝试使用代码时,我遇到了doc.getActiveSection()
的自动完成问题。根据{{3}},最近发生了变化。
将Document.getActiveSection()重命名为getBody()。
您应该相应地更新您的代码。