简体   繁体   中英

bulk find and replace in google docs using sheet and app script

Thank you in advance.

I am trying to multiple finds and replace google docs with a reference google sheet

Find            |  Replace  
----------------------------
bill number one | Bill No. 1
Bill number one | Bill No. 1
Bill number 1   | Bill No. 1
Bill Number One | Bill No. 1
Bill Number 1   | Bill No. 1
function replMyText(){
  var ss=SpreadsheetApp.openById('1-WblrS95VqsM5eRFkWGIHrOm_wGIPL3QnPyxN_j5cOo');
  var sh=ss.getSheetByName('find and replace');
  var doc=DocumentApp.getActiveDocument();
  var docrange=doc.getBody()
  var rgtxt=doc.getBody();//text to replace
  var rgrep=sh.getRange('A2:B103');//replacement table
  var txtA=rgtxt.getText();
  var repA=rgrep.getValues();
  
  for(var i=0;i<txtA.length;i++){
    for(var j=0;j<repA.length;j++){
      if(txtA[i][0]==repA[j][0]){
        txtA[i][0]=repA[j][1];
      }
    }
  }
  rgtxt.setText(txtA);
}

I did not get the output.

I believe your goal as follows.

  • You want to replace the text in Google Document using the values retrieved from Google Spreadsheet.
  • The columns "A" and "B" in Google Spreadsheet are the search text and the replace text, respectively.

In this case, I thought that replaceText() might be able to be used. When your script is modified, it becomes as follows.

Modified script:

function replMyText() {
  var ss = SpreadsheetApp.openById('1-WblrS95VqsM5eRFkWGIHrOm_wGIPL3QnPyxN_j5cOo');
  var sh = ss.getSheetByName('find and replace');
  var doc = DocumentApp.getActiveDocument();
  var rgtxt = doc.getBody();
  var rgrep = sh.getRange('A2:B103');
  var repA = rgrep.getValues().filter(r => r.every(c => c.toString()));
  repA.forEach(e => rgtxt.replaceText(...e));
}

Reference:

If you would like to do this without a script, you can do it right in Google Sheets with the powerful ARRAYFORMULA() function

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM