首页 > 解决方案 > 如何读取 Google Docs 上的数据并将其写回 Google Sheets(使用应用脚本)

问题描述

我是一个使用应用程序脚本的新手,并且陷入了以下困境。我有一个 google 表格,其中包含具有相同格式的 google 文档的 url 列表。我希望能够阅读文档并在新列中写回谷歌表格,每个网址的特定段落和行中的文本。使用下面的代码,我可以从文档中读取我想要的内容,但不完全是我打算做的事情。我想我需要为工作表上的每个 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);

}

标签: google-apps-scriptgoogle-docs

解决方案


这样的事情会做:

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

编码:

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

}

推荐阅读