【问题标题】:Use Google Script to Edit and Delete Tables in Document使用 Google Script 编辑和删除文档中的表格
【发布时间】:2021-12-02 16:00:58
【问题描述】:

下面是一个创建示例文档并向其中插入三个表格的函数。三个现有表在日志中显示为 [Table, Table, Table],正确计数为 3。如何“访问”或“选择”这些表进行编辑?我想从某人那里收到在表 1 的末尾添加一行所需的代码,然后是 删除表 2 的代码。如果我明白这一点,我想我会得到我需要的。

function create_edit_delete_table() {

// Create sample table and get id
var docId = DocumentApp.create('SAMPLE_DOCUMENT').getId();

// Get doc body
var body = DocumentApp.openById(docId).getBody();

// Create a two-dimensional array containing the cell contents.
var cells = [
  ['Row 1, Cell 1', 'Row 1, Cell 2'],
  ['Row 2, Cell 1', 'Row 2, Cell 2']
];

// Build three tables from the array and insert into document.
body.appendTable(cells);
body.appendTable(cells);
body.appendTable(cells);

var tables = DocumentApp.openById(docId).getBody().getTables();
var tables_ct = DocumentApp.openById(docId).getBody().getTables().push();

Logger.log(tables);
Logger.log(tables_ct);

//Looking for code to add a blank row to the end of first table.

//Looking for code to delete the second table.

}

谢谢!

【问题讨论】:

  • 你有没有尝试过?
  • 是的。实际上,很多事情,包括改编我在网上找到的脚本。删除表的示例之一是:stackoverflow.com/questions/58989022/…。不幸的是,我无法让它与 removeFromParent() 或 removeChild() 一起工作。这些函数假定我手头有表,但到目前为止我无法正确地将它们“连接”到表。
  • 请在每个帖子中只问一个问题。关注问题 1,tables 是一个数组。有关 js 数组的免费资源,请参阅 tag info page。选择 table1 很简单,就像tables[0]。然后,您将在文档中搜索可用的表方法。

标签: google-apps-script google-docs


【解决方案1】:

将空行追加到表 1。使用这个:

function appendRow() {
  var body = DocumentApp.openById("doc id").getBody();
  var tables = body.getTables();
  var firstTable = tables[0].appendTableRow();
  firstTable.appendTableCell();
  firstTable.appendTableCell();
}

删除文档中的第二个表。使用这个:

function deleteTable(){
  var body = DocumentApp.openById("doc id").getBody();
  var tables = body.getTables();
  tables[1].removeFromParent();
}

注意:getTables()数组中表格对象的顺序是根据表格在您的文档中的位置(从上到下),0为起始索引。

例子:

之前:

执行 appendRow() 后:

执行 deleteTable() 后:

参考资料:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-05
    • 2013-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多