2015-12-21 71 views
2

我正在製作合併代碼,以從我的電子表格中提取數據並在Google文檔中填充合併代碼。我無法正確寫入的部分代碼是將代碼寫回Google Doc的部分。我已經能夠找到標籤,但代碼不能代替它們。使用RegEx替換電子表格數據的Google Doc文本

這是我到目前爲止寫的。

function mergeApplication() { 
    var ss = SpreadsheetApp.getActiveSpreadsheet(); 
    var sheet = ss.getSheetByName("Merge Data"); 
    var range = sheet.getActiveRange(); 
    var formSheet = ss.getSheetByName("Form Responses"); 
    var lastRow = formSheet.getLastRow(); 
    var lastColumn = sheet.getMaxColumns(); 

    function checkAndComplete() { 
    var urlColumn = lastColumn; 
    var checkColumn = (urlColumn - 1); 
    var checkRange = sheet.getRange(2, checkColumn, (lastRow - 1), 1); 
    var check = checkRange.getBackgrounds(); 
    var red = "#ff0404"; 
    var yellow = "#ffec0a"; 
    var green = "#3bec3b"; 
    for (var i = 0; i < check.length; i++) { 
     if (check[i] == green) { 
     continue; 
     } else { 
     var statusCell = sheet.getRange((i+2), checkColumn, 1, 1); 
     var urlCell = sheet.getRange((i+2), urlColumn, 1, 1); 
     var dataRow = sheet.getRange((i+2), 1, 1, (lastColumn - 2)); 

     function mergeTasks() { 
      function docCreator() { 
//   var templateConditionRange = sheet.getRange((i+2), column); 
//   var templateConditionCheck = templateConditionRange.getValues(); 
      var docTemplate1 = DriveApp.getFileById(id); 
      //   var docTemplate2 = DriveApp.getFileById(id); 
      //   var docTemplate3 = DriveApp.getFileById(id); 
      var folderDestination = DriveApp.getFolderById(id); 
      var clientName = sheet.getRange((i+2), 3).getValue(); 
      var date = sheet.getRange((i+2), 1).getValue(); 
      //   if (templateConditionCheck[i] == "") { 
      var docToUse = docTemplate1; 
      //   } 
      //   if (templateConditionCheck[i] == "") { 
      //   var docToUse = docTemplate2; 
      //   } 
      //   if (templateConditionCheck[i] == "") { 
      //   var docToUse = docTemplate3; 
      //   } 
      var docName = "Merge Tester Doc for " + clientName + " [" + date + "]"; 
      var docCopy = docToUse.makeCopy(docName, folderDestination); 
      var docId = docCopy.getId(); 
      var docURL = DriveApp.getFileById(docId).getUrl(); 
      var docToSend = DriveApp.getFileById(docId); 
      var docBody = DocumentApp.openById(docId).getBody().getText(); 

      function tagReplace() { 
       var taggedArray = [docBody.match(/\<{2}[\w\d\S]+\>{2}/g)]; 
       var headerArray = [sheet.getRange(1, 1, 1, (lastColumn - 2)).getValues()]; 
       var dataArray = [dataRow.getValues()]; 
       var strippedArray = []; 
       Logger.log("The preliminary length of taggedArray is " + taggedArray.length); 
       Logger.log(taggedArray); 

       function tagStrip() { 
       for (var t = 0; t < taggedArray.length; t++) { 
        var strippedString = taggedArray[t].slice(2, -3).toString(); 
        strippedArray.push(strippedString); 
        Logger.log("The current strippedArray length is " + strippedArray.length); 
       } 
       Logger.log("The final strippedArray length is " + strippedArray.length); 
       Logger.log("The final taggedArray length is " + taggedArray.length); 
       Logger.log("The final, completed strippedArray is " + strippedArray); 
       } 

       function dataMatch() { 
       for (var s = 0; s < strippedArray.length;) { 
        for (var h = 0; h < headerArray.length;) { 
        if (strippedArray[s] == headerArray[h]) { 
         docBody.replaceText(taggedArray[s].String(), dataArray[h].String()); 
         h=0; 
         s++; 
        } else { 
         h++; 
        } 
        } 
       } 
       } 
       tagStrip; 
       dataMatch; 
      } 

      function emailCreator() { 
       var emailTag = sheet.getRange((i+2), (urlColumn - 2)).getValue(); 
       var emailBody = HtmlService.createHtmlOutputFromFile("Email Template").getContent(); 
       var personalizers = clientName + " [" + date + "]"; 
       var subject = "Merge Tester Email for " + personalizers; 
       MailApp.sendEmail(emailTag, subject, emailBody, { 
       name: "Christopher Anderson", 
       attachments: [docToSend], 
       html: emailBody, 
       }); 
      } 
      tagReplace(); 
      statusCell.setBackground(yellow); 
      emailCreator(); 
      urlCell.setValue(docURL) 
      } 
      statusCell.setBackground(red); 
      docCreator(); 
      statusCell.setBackground(green); 
     } 
     mergeTasks(); 
     } 
    } 
    } 
    checkAndComplete(); 
} 

問題部分是在這裏:

function tagReplace() { 
       var taggedArray = [docBody.match(/\<{2}[\w\d\S]+\>{2}/g)]; 
       var headerArray = [sheet.getRange(1, 1, 1, (lastColumn - 2)).getValues()]; 
       var dataArray = [dataRow.getValues()]; 
       var strippedArray = new Array(); 
       Logger.log("The preliminary length of taggedArray is " + taggedArray.length); 
       Logger.log(taggedArray); 
       function tagStrip() { 
       for (var t = 0; t < taggedArray.length; t++) { 
        var strippedString = taggedArray[t].slice(2, -3).toString(); 
        strippedArray.push(strippedString); 
        Logger.log("The current strippedArray length is " + strippedArray.length); 
       } 
       Logger.log("The final strippedArray length is " + strippedArray.length); 
       Logger.log("The final taggedArray length is " + taggedArray.length); 
       Logger.log("The final, completed strippedArray is " + strippedArray); 
       } 
       function dataMatch() { 
       for (var s = 0; s < strippedArray.length;) { 
        for (var h = 0; h < headerArray.length;) { 
        if (strippedArray[s] == headerArray[h]) { 
         docBody.replaceText(taggedArray[s].String(), dataArray[h].String()); 
         h=0; 
         s++; 
        } else { 
         h++; 
        } 
        } 
       } 
       } 
       tagStrip; 
       dataMatch; 
      } 

,它甚至沒有登錄具有strippedArray做任何事情。 它似乎完全跳過了該部分。 我是否正在使用完成此任務的正確方法和/或是否有更簡單的方法?

值得一提的是,我在doc中的標籤在他們周圍有2個「<>」。這就是我的RegEx看起來如何的原因。 另外,當記錄taggedArray.length時,它返回值1

+0

你是否通過調試器運行代碼? 'taggedArray.length'是否可以是0? –

+0

調試器回來乾淨。當我登錄'taggedArray'時,它返回'.length'爲1.它不會記錄任何與'strippedArray'有關的事情。 – MasterCrander

+0

出於好奇你可以使用body.replaceText()函數嗎?它可能更可靠。 https://developers.google.com/apps-script/reference/document/body#replacetextsearchpattern-replacement –

回答

1

你從來沒有真正調用應該在strippedArray上工作的tagStrip。
你用function tagStrip(){}聲明它,後來你用tagStrip;引用函數,但你實際上從來沒有真的調用它。 dataMatch也是如此。

嘗試寫

tagStrip(); 
dataMatch(); 

調用兩個函數如果不包括你不叫的,你只要運行函數對象作爲語句的括號內。

+0

哦......哇......我現在感覺很蠢。謝謝。我馬上試試這個。如果出現新問題,我會結束這個問題並詢問另外一個問題。接得好。 – MasterCrander

0

這是我在我的附加組件中使用的一部分代碼簡單發送,我使用相同的< < >>合併標籤。

//copy template 
    var mDocDrive = doc.makeCopy(title, folder); 
    var mDoc = DocumentApp.openById(mDocDrive.getId()); 
    var mDocDriveApp = DriveApp.getFileById(mDoc.getId()); 
    var docToAttach = mDoc.getUrl(); 
    var driveToShare = mDocDriveApp; 

    // replace text inside template 
    var body = mDoc.getBody(); 
    body.replaceText("<<SS Title>>", title); 
    body.replaceText("<<timestamp>>", lastR.timestamp); 
    body.replaceText("<<username>>", lastR.email); 

    for (i in lastR.theResponses){ 
    var cur = lastR.theResponses[i]; 
    var name = cur.title; 
    name = name.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); // this will allow fields that include special characters. 
    var response = cur.response; 
    var searchPattern = "<<"+name+">>"; 
    body.replaceText(searchPattern, response); 
    } 

    // this will replace any unused tags with nothing. 
    var ques = getQuestionList(); 
    for (j in ques){ 
    var curq = ques[j].name; 
    curq = curq.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); 
    var searchPattern2 = "<<"+curq+">>"; 
    body.replaceText(searchPattern2, ""); 
    } 

    mDoc.saveAndClose(); 



    //create pdf 
    if (mmDefaults.shareAs == "pdf"){ 
    // uncomment if you want to make the pdf in the merge folder 
    var asPdf = mDoc.getAs('application/pdf'); 
    asPdf.setName(mDoc.getName()+ ".pdf"); 
    var pdf = DriveApp.createFile(asPdf); 
    folder.addFile(pdf); 
    DriveApp.removeFile(pdf); 
    mDocDriveApp.setTrashed(true); 
    var docToAttach = pdf; 
    driveToShare = pdf; 
    } 
+0

這很不錯。你在尋找的東西似乎有多餘。你有一些具體的描述,然後有兩個循環來捕捉可能發生的情況。爲什麼不使用一個循環來捕獲所有標籤?即使你的模板有表單沒有數據的標籤,它會不會被''「'填充?既然它會讀爲空單元格,並且默認爲'「」'? – MasterCrander

+0

這是因爲我使用的是表單的響應,而不是表單。如果用戶不回答問題,則表單響應不存在,相比於從表單中拉出時只是空白。所以我添加了額外的循環來刪除任何人沒有回答的問題的合併標籤。 –

相關問題