Search code examples
google-apps-scriptgoogle-docs

How to read data on Google Docs and write it back in Google Sheets (using app script)


I'm a newbie with app script and got stuck with the below. I have a google sheet with a list of urls of google docs that have identical formatting. I want to be able to read the docs and write back to the google sheet in a new column, the text from a specific paragraph and row for each url. With the below code, I am able to read what I want to from the a doc but not exactly what I intend to do. I think I need to create a variable for each url on my sheet to start with. Can someone help with this please? Thanks very much in advance.

function doc_details() {      
  var doc = DocumentApp.openByUrl("this is where I enter the doc url");
  var body = doc.getBody();
  // select the table
  var table= body.getTables()[0];
// select the row
  var row = table.getRow(3);
  var res = row.getText();


  Logger.log(res);

}

Solution

  • Something like this would do:

    1. Get the urls from the sheet.
    2. Then for each url -> Do your code and push the result to the output array.
    3. Write the array to the sheet in column B.

    The code:

    function doc_details() {
      const ss = SpreadsheetApp.getActiveSpreadsheet();
      const sheetWithUrls = ss.getSheetByName('SheetWithUrls');
      const urls = sheetWithUrls.getRange('A2:A').getValues()
        .flat()
        .filter(url => url != '');
    
      const output = []
    
      urls.forEach(url => {
        const doc = DocumentApp.openByUrl(url);
        const table = doc.getBody().getTables()[0];
        const row = table.getRow(3);
        const res = row.getText();
        output.push([res])
      })
    
      //Starting from the second row / In the second column (B)
      sheetWithUrls.getRange(2,2,output.length,1).setValues(output);
    
    }