google-sheetsgoogle-apps-scriptgoogle-docsgoogle-apps

Exception: Unexpected error while getting the method or property openById on object DocumentApp while trying to open Google doc file


I am trying to open a doc file and replace a value using the simple snippet:

function openFile(){
  var doc = DocumentApp.openById("docId");
  var body = doc.getBody();
  body.replaceText("Name of Accountant","ABC");
}

I got to know from this thread that error is due to e-signature that I am using in my doc file. The error looks like this:

Exception: Unexpected error while getting the method or property openById on object DocumentApp.

The table in my doc file, you can find sample file here:

E-Sign

Is there a way that I can open and get the body of the doc file without removing the e-signature from the table? Any suggestion would be much appreciated.


Solution

  • You can use the Google docs API to get the data directly using UrlFetchApp or by using Advanced Google services.

    For eg, using Advanced Google services(with identifier Docs), you can get the 4th index's table like this:

    function getDocData(){
      const doc = Docs.Documents.get("1RMCxm0SsqzmsSbx16kTho7GEYOOapoKQbdf0jwNbGMc");
      const table = doc.body.content.find(section => section.startIndex === 4).table;
      const row3c2_content = table.tableRows[2].tableCells[0].content[0].paragraph.elements;
      console.info(row3c2_content)
    }
    

    To replace text, issue a replaceAllRequest,

    const 
      text = 'Name of Accountant',
      replaceText = 'ABC';
    Docs.Documents.batchUpdate(
      {
        requests: [
          {
            replaceAllText: {
              containsText: { text, matchCase: true },
              replaceText,
            },
          },
        ],
      },
      "1RMCxm0SsqzmsSbx16kTho7GEYOOapoKQbdf0jwNbGMc"
    );