复制文档页面并替换每页上的文本

时间:2012-05-30 23:29:54

标签: google-apps-script

我正在尝试创建一个脚本,该脚本将获取Google文档模板文档,制作副本,使用电子表格中某行的信息替换某些文本,附加另一页,将文本替换为下一行中的信息。电子表格,附加另一页等。

这是我到目前为止所做的:

// Global variables 
var templateDocID = ScriptProperties.getProperty("backRxRequestDocID");
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var activeSheetName = sheet.getName();
var user = Session.getUser().getEmail();

function requestGen3() {
  var physName = ["doc john", "doc evan", "doc jane"];
  var physAddr1 = ["fake st.", "faker st.", "fakest st."];
  var physAddr2 = ["ste 100", "", "ste 209"];
          var physCity = ["SLC", "Provo", "Orem"];
  var physState = ["UT", "AZ", "NV"];
  var physZip = ["84049", "84044", "84601"];
          var physPhone = ["8015555555", "7206666666", "4803333333"];
  var ptName = ["ed", "sue", "izzy"];
  var ptDOB = ["12/10/1979", "1/1/2001", "45/94/4561"];
  // Get document template, copy it as a new temp doc, and save the Doc’s id
  var docID = DocsList.getFileById(templateDocID).makeCopy().getId();
  var doc = DocumentApp.openById(docID);
  var body = doc.getActiveSection();
  var pars = doc.getParagraphs();
  var bodyCopy = body;
  for (var i = 0; i < physName.length; ++i) {
    // Replace place holder keys,  
    body.replaceText('%PHYS_NAME%', physName[i]);
    body.replaceText('%PHYS_ADDR1%', physAddr1[i]);
    body.replaceText('%PHYS_ADDR2%', physAddr2[i]);
    body.replaceText('%PHYS_CITY%', physCity[i]);
    body.replaceText('%PHYS_STATE%', physState[i]);
    body.replaceText('%PHYS_ZIP%', physZip[i]);
    body.replaceText('%PHYS_PHONE%', physPhone[i]);
    body.replaceText('%PT_NAME%', ptName[i]);
    body.replaceText('%PT_DOB%', ptDOB[i]);    
    doc.appendPageBreak();
    for (var j = 0; j < pars.length; ++j) {
      doc.appendParagraph(pars[j].copy());
    }
  }

  // Save and close the document
  doc.saveAndClose();
}

我浏览了电子表格中的阅读教程,但似乎无法使getRowsData()getObjects()正常工作。我上面的脚本正在正确创建文档,但没有将第二组信息插入第二页,第三组则插入第三页等。

2 个答案:

答案 0 :(得分:3)

您必须在复制段落后才替换文本,因为如果您之后执行此操作,占位符将被替换,并且不会出现在下一个副本中。你可以这样做:

//...
var pars = doc.getParagraphs();
for( var i in pars ) //loop to keep a copy of the original paragraphs
  pars[i] = pars[i].copy();

for( var i = 0; i < physName.length; ++i ) {
  body.replaceText('%PHYS_NAME%', physName[i]);
  //do all your replaces...
  if( i != physName.length-1 ) { //has next?
    doc.appendPageBreak();
    for( var j in pars )
      doc.appendParagraph(pars[j].copy());
  }
}
doc.saveAndClose();

答案 1 :(得分:0)

以下代码将读取您的电子表格并创建一个名为data的矩阵。

var sh = SpreadsheetApp.getActive().getActiveSheet();
var lastRow = sh.getLastRow();
var lastCol = sh.getLastColumn();
var data = sh.getRange(1, 1, lastRow, lastCol).getValues();