0

In a Spreadsheet cell I have a link to a Google doc and I want to recuperate it in order to open the Google Doc and modify it. So in my cell I've put this format https://docs.google.com/document/d/1Gb48I...... (without the /edit in the end) and I've tried

            var body = '=HYPERLINK("'data[n][COLUMN_URL-1]'+'/edit'")'.getBody();
            var body = '=HYPERLINK("'data[n][COLUMN_URL-1]'+'/edit'")'.getBody();

           // this one works but I want to use data[n][COLUMN_URL-1] because I have several Google Docs links
var body = DocumentApp.openByUrl('https://docs.google.com/document/d/1Gb48IXos......../edit').getBody(); 
            if(body){
//edit the Google doc

If you have ideas what to do thank you because with the concatenation of the /edit(3rd line of code) it works

Edit: The cell is not formatted(hyperlinked)/formula i have only the https://...

Edit 2: I've tried with a code from Suhail Ansari thank you but I have an error that the document is missing and I don't have nothing for the logs if you have others ideas:

var COLUMN_URL = 10 ;

function getIdFrom(url) {
  var id = "";
  var parts = url.split(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/);
  if (url.indexOf('?id=') >= 0){
    id = (parts[6].split("=")[1]).replace("&usp","");
    return id;
  } else {
    id = parts[5].split("/");
    //Using sort to get the id as it is the longest element. 
    var sortArr = id.sort(function(a,b){return b.length - a.length});
    id = sortArr[0];
    return id;
  }
}

var sheet = SpreadsheetApp.openById(SPREADSHEET_ID).getSheetByName(SHEET_NAME);
  var numRows = sheet.getLastRow();
  var lastColumn = sheet.getLastColumn();
  var data = sheet.getRange(1,1,numRows,lastColumn).getDisplayValues();
   for(n=1;n < data.length;n++) {
  var URL =data[n][COLUMN_URL-1];
        Logger.log('The URL  ',URL);
        var id = getIdFrom(URL);
        Logger.log('The ID  ',id);
        var body = DocumentApp.openById(id).getBody();
        
        
        if(body)
        {......//edit Google Doc

This is the 10 column with the URLs from the Google Docs  here

In fact I have docs.google.com/open?id=1qo0B_HCbjcBrYyJ ... as URL for the others rows I tried to do by hand for 3rd one as you can see in the picture

Edit 3: So I am very confused in this moment because the column I have in the spreadsheet commes from a loop where I put the URL of the Google Docs in the cell like this : var trange = sheet.getRange.. trange.setValue(doc.getUrl()); and now if i look at the table i have the links in this format

https://docs.google.com/open?id=1RYRVotAq6IOz5tys1krnENfgN_pU0KYuUzR24i so now if i want to get back the Google Doc I have the following :

 //  var body = DocumentApp.openByUrl('https://docs.google.com/open?id=1Xb4QjiWwpn2TJ8-9kkIhU6m1rgmb48g6xYVopN').getBody();
            //var body = DocumentApp.openByUrl('https://docs.google.com/1Xb4QjiWwpn2TJ8-9kkIhU6m1rgmb48g6xYVopN/edit').getBody();
            var body = DocumentApp.openByUrl('https://docs.google.com/document/d/1Xb4QjiWwpn2TJ8-9kkIhU6m1rgmb48g6xYVopN/edit').getBody();

only the 3rd one works.Where I am doing wrong? Because I want to
for(n=1;n < data.length;n++) {... make a loop for and var URL = data[n][COLUMN_URL-1];

ana maria
  • 353
  • 1
  • 4
  • 22
  • 1
    `'=HYPERLINK("' + .... + '")'` is just a string. It doesn't make Apps Script create a hyperlink and retrieve data from that particular URL and instantiate a `Document` class object (so your call to `.getBody()` will fail). Generic URL handling in Apps Script is via `UrlFetchApp`. Class-specific URL handling is done via that class's `openByUrl` method - if it even has one. – tehhowch Jun 18 '18 at 11:45
  • Thanks I've edited my post because I have some questions regarding openByUrl which I've tried and does not work in my purpose I want to for(n=1;n < data.length;n++) {... make a loop for and var URL = data[n][COLUMN_URL-1]; and then var body = DocumentApp.openByUrl(URL); – ana maria Jun 18 '18 at 12:32
  • 1
    Does your regex actually parse the ID correctly? You will get errors for incorrect IDs, and you do not show any results from the parsing step. Consider logging to Stackdriver so that your logs are persistent (for a month at least) – tehhowch Jun 18 '18 at 12:47
  • The erors I have with this one it's missing document so every time I write in a cell var doc = DocumentApp.openById(docIDs[i]); trange = sheet.getRange(insertion_position, j+1); //la première cellule trange.setValue(doc.getUrl()); i have the url with /open?id= ......and then when i try the loop for n >>>> var URL = data[n][COLUMN_URL-1]; var body = DocumentApp.openByUrl(URL).getBody(); it does't find the file – ana maria Jun 19 '18 at 07:32
  • 1
    Placing code in comments does not help you. Adding edit after edit to your question does not help you. You need to ask a specific and clear question: what are you trying to do, how are you trying to do it, what actually happens, and where in the process is it going wrong. It sounds like at one point in your process you have the document ID, and write on the sheet the document URL. Why not write both? Then you can avoid trying to parse the id from the URL. – tehhowch Jun 19 '18 at 11:21
  • Thank you very much I will try to do that. – ana maria Jun 19 '18 at 13:26

1 Answers1

1

You could add some code for getting the Doc ID from the URL and then open the doc by using

DocumentApp.openById(id);

Here is a link to do that.

A sample code below with help from the above linked answer:

function myFunction() {
  var URL = SpreadsheetApp.getActiveSheet().getRange('A1').getValue();
  var id = getIdFrom(URL);

  var doc = DocumentApp.openById(id);

  var body = doc.getBody();
  Logger.log(body.getText());
}


function getIdFrom(url) {
  var id = "";
  var parts = url.split(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/);
  if (url.indexOf('?id=') >= 0){
     id = (parts[6].split("=")[1]).replace("&usp","");
     return id;
   } else {
   id = parts[5].split("/");
   //Using sort to get the id as it is the longest element. 
   var sortArr = id.sort(function(a,b){return b.length - a.length});
   id = sortArr[0];
   return id;
   }
 }

Demo Google Sheet

  • Thank you very much I've tried your code but it does't work it says a document is missing maybe it was deleted.I've edited the post also if you have others ideas or not passing through the id directly pass the url it will be more simple no? – ana maria Jun 18 '18 at 10:54
  • In fact I have https://docs.google.com/open?id=1qo0B_HCbjcBrYyJ ... as URL for the others rows I tried to do by hand for 3rd one as you can see in the picture – ana maria Jun 18 '18 at 11:01
  • 1
    Why don't you just try once to test it with hard-coded URL value. For example, set _var URL = ''https://docs.google.com/open?id=1qo0B_HCbjcBrYyJ" var id = getIdFrom(URL); Logger.log('The ID ',id); var body = DocumentApp.openById(id).getBody();_ – Suhail Ansari Jun 18 '18 at 11:08
  • So I've tried with this one : var URL ="docs.google.com/open?id=1Xb4QjiWwpn2TJ8-9kkIhU6m1rgmb48g6xYVopNUQJb" // data[n][COLUMN_URL-1]; Logger.log('The URL ',URL); var id = getIdFrom(URL); Logger.log('The ID ',id); var body = DocumentApp.openById(id).getBody(); but it's the same thing as before no messages for the logs and if i write a message in the doc it is not written – ana maria Jun 18 '18 at 12:06
  • So i did as in the demo Google Sheet you posted and as i put in the cell the https:...open?=id.... and then var sheet = SpreadsheetApp.openById(SPREADSHEET_ID).getSheetByName(SHEET_NAME); var numRows = sheet.getLastRow(); var lastColumn = sheet.getLastColumn(); var data = sheet.getRange(1,1,numRows,lastColumn).getDisplayValues(); var URL = data[0][0]; Logger.log(URL); // it does't work var doc = DocumentApp.openByUrl(URL); var body = doc.getBody(); Logger.log(body.getText()); **/ it is not capable to open the file but if i use the id it works – ana maria Jun 19 '18 at 09:36
  • What is the proble i'm becoming insane normally it is a URL and the fact that i have ?open= would be a problem? – ana maria Jun 19 '18 at 09:37