google-apps-script - ้如何通过 Google App Script 将 Google Document Table 的部分内容复制到 Google Spreadsheet
问题描述
有什么方法可以在 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 文档和示例输出图像中看到您的示例电子表格,但我相信您的目标如下。
修改点:
- 在您的脚本中,检索第二个表。在您的示例文档中,发生错误。
- 在您的情况下,我认为需要从每个单元格中检索值。但是在您的脚本中,这些值是直接从行中检索的。
- 在您的脚本中,仅从行中检索值。为了实现您的目标,需要将检索到的值从 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 文档。
参考:
推荐阅读
- python - 用于情感分析python的标签数据训练
- java - MainActivity RecyclerView 和房间数据库崩溃 - Java
- elasticsearch - Elasticsearch _id 作为 MD5 哈希或文档字段
- varnish - 对禁止对象使用宽限模式
- wordpress - 无限 URL 问题,URL 不应该随着页面滚动而改变
- r - 点模式的最近邻距离(按年份)
- java - 如何从 AnyLogic 数据库表中读取分布信息
- .net - 如何在 .NET5 中存储用户定义的设置?
- javascript - Nextjs 12:为什么激活实验性 React 并发特性会禁用 API 路由?
- angular - 如何将 @google/model-viewer 添加到 Angular 应用程序