1

这是我的代码,我不知道为什么 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 以及其他几个选项。

任何想法为什么这不起作用?

预先感谢

4

1 回答 1

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(). 根据2013 年 4 月 15 日的发行说明,事实证明最近发生了变化。

将 Document.getActiveSection() 重命名为 getBody()。

您应该相应地更新您的代码。

于 2013-05-01T01:33:20.827 回答