如何读取 Google 文档中的数据并将其写回 Google 表格(使用应用脚本)

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

我是应用脚本的新手,遇到了以下问题。我有一个 google sheet,其中包含具有相同格式的 google 文档的 url 列表。我希望能够阅读文档并写回新列中的 google sheet,每个 url 的特定段落和行中的文本。使用下面的代码,我可以从文档中读取我想要的内容,但不完全是我打算做的。我想我需要为 sheet 上的每个 url 创建一个变量来开始。有人可以帮忙吗?非常感谢。

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);

}

像这样的事情会做:

  1. 从 sheet 中获取 url。
  2. 然后对每个 url -> 执行您的代码并将结果推送到输出数组。
  3. 将数组写入B列的sheet

代码:

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);

}