繁体   English   中英

้如何通过 Google App Script 将 Google Document Table 的部分内容复制到 Google Spreadsheet

[英]้How to Copy Some Content of Google Document Table to Google Spreadsheet By Google App Script

有什么方法可以在 Google Document Table 中选择一些内容并通过 Google App Script 复制到 Google Spreadsheet

跟随我的照片创意

我想将红框/蓝框中的一些内容复制到 Google 电子表格中,包括列名中的数据:级别、到期日 1、到期日 2

我从以下代码大纲开始:

function Tables() {
var doc = DocumentApp.getActiveDocument().getBody();  
var tables = doc.getTables()[1]; 
for (var i = 0; i < tables.getNumRows(); ++i) {
  var cell = tables.getRow(i);
  var text =cell.getText();
  Logger.log(text);
} 
}

虽然我看不到您的示例电子表格,但从您的示例 Google 文档和示例 output 图像中,我相信您的目标如下。

  • 您想从 Google 文档中的第一个表中检索值,并通过如下转换值将这些值放入 Google 电子表格。

    • 在此处输入图像描述

    • 在此处输入图像描述

修改点:

  • 在您的脚本中,检索第二个表。 在您的示例文档中,发生错误。
  • 在您的情况下,我认为需要从每个单元格中检索值。 但是在您的脚本中,这些值是直接从行中检索的。
  • 在您的脚本中,仅从行中检索值。 为了实现您的目标,需要将检索到的值从 Document 转换为 Spreadsheet。

当以上几点反映到脚本时,它变成如下。

修改后的脚本:

请将以下脚本复制并粘贴到脚本编辑器并设置变量并运行脚本。 关于excludeTexts的变量,在这种情况下,这些值来自您的示例 Google 文档。 当您更改文档表中的排除文本行时,请修改值。

function myFunction() {
  const documentId = "###";  // Please set Document ID.
  const spreadsheetId = "###";  // Please set Spreadsheet ID of the destination Spreadsheet.
  const sheetName = "Sheet1";  // Please set the sheet name of the destination sheet.
  const excludeTexts = ["Part A:", "Part B:", "Part C:"];  // Please set the exclude texts.

  // 1. Retrieve values from 1st table from Document and create an array for putting to Spreadsheet.
  // const body = DocumentApp.getActiveDocument().getBody(); // If you copy and paste the script to the container-bound script of Document, you can use this line instead of "DocumentApp.openById(documentId).getBody()".
  const body = DocumentApp.openById(documentId).getBody();
  const table = body.getTables()[0];
  let values = [];
  for (let r = 0; r < table.getNumRows(); r++) {
    const cell = table.getRow(r);
    const row = [];
    for (let c = 0; c < cell.getNumCells(); c++) {
      const text = cell.getCell(c).getText().trim();
      row.push(r > 0 && c == 1 ? text.split("\n").map(e => e.trim()).filter(e => !excludeTexts.includes(e)) : text);
    }
    values = values.concat(Array.isArray(row[1]) ? row[1].map((e, i) => i == 0 ? [row[0], e, ...row.slice(2)] : ["",e,...Array(row.slice(2).length).fill("")]) : [row]);
  }
  console.log(values)

  // 2. Put the created array to Spreadsheet.
  const sheet = SpreadsheetApp.openById(spreadsheetId).getSheetByName(sheetName);
  sheet.getRange(1, 1, values.length, values[0].length).setValues(values);
}
  • 为您的 Google 文档运行上述脚本时,将获得顶部图像的示例情况。

笔记:

  • 此示例脚本可用于您的示例 Google 文档。 如果您的 Document 的结构发生更改,则可能需要修改脚本。 所以请注意这一点。 当您测试此脚本时,请使用您的示例 Google 文档。

参考:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM