如何在Google Apps脚本中获取选定的表格 [英] How to get selected table in Google apps script

查看:89
本文介绍了如何在Google Apps脚本中获取选定的表格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个脚本,该脚本将使用用户选择的表.但是,使用DocumentApp.getActiveDocument().getSelection().getRangeElements()将仅获取单个单元格.我以为我可以重建表格,但是所有单元格都在一个长列表中,没有行或列的信息,用户应该能够选择任何高度/宽度的表格,而不必告诉程序尺寸是多少是.我还考虑过让程序自动选择前面的某个表,以便将该表视为一个表而不是单个单元格,但这仍然会选择单个单元格(但不是所有的单元格都有些特殊.)感谢您的反馈/帮助!

I am writing a script that will use a table that a user has selected. However, using DocumentApp.getActiveDocument().getSelection().getRangeElements() will get only the individual cells. I thought I could just reconstruct the table, but the cells are all in one long list with no info on rows or columns, and the user should be able to select a table of any height/width without having to tell the program what the dimensions are. I also thought about having the program automatically select a bit ahead, in order to treat the table as a table and not individual cells, but this still selects individual cells (but not all of them which is a bit peculiar.) Thanks for any feedback/help!

推荐答案

替换通过将光标放在任何单元格中选择的表

我刚刚为要替换的表格组成了一个二维数组.

Replacing a table selected by placing cursor in any cell

I just made up a two dimensional array for the table to be replaced with.

如果尝试将第一个元素转换为Table(),则会收到错误"PARAGRAPH无法转换为TABLE." ,然后添加另一个getParent(),您将得到错误'TABLE_CELL无法转换为TABLE. ',然后添加另一个getParent(),您将得到错误'TABLE_ROW无法转换为TABLE.',最后添加另一个getParent()最终通过了手套并替换表格.您可以将光标放在表中的任何单元格中.这是一个小技巧,但最终似乎可行.如果不知道如何使用Google提供的调试资源,要弄清这一点将更加困难.

If you try to cast the first element asTable() you'll get the error 'PARAGRAPH can't be cast to TABLE.' then if add another getParent() you'll get the error 'TABLE_CELL can't be cast to TABLE. ' and then add another getParent() and you'll get the error 'TABLE_ROW can't be cast to TABLE.' and finally adding yet another getParent() finally passes through the gauntlet and replaces the the table. You can put the cursor in any cell in the table. It was a bit of a hack but in the end it seems to work. It would have been much more difficult to figure this out without knowing how to use the debug resources that Google provides.

function replaceTableAtCursor(){
  var doc=DocumentApp.getActiveDocument();
  var body=doc.getBody();
  var el=doc.getCursor().getElement().getParent().getParent().getParent();//element/cell/row/table
  var table=el.asTable();
  var t=[];//This is the table I used. Any 2D array will work like the ones you can get from getValues() method from spreadsheets.
  for(var i=0;i<3;i++){
    t[i]=[];
    for(var j=0;j<3;j++){
      t[i][j]=Utilities.formatString('i:%s,j:%s',i,j);
    }
  }
  var childIndex=body.getChildIndex(el)
  table.clear();
  body.insertTable(childIndex,t)  
}

  • 位置类别
  • 疑难解答
  • 在适当位置编辑表的示例
    • Position Class
    • Trouble Shooting
    • Example That Edits a Table in Place
    • 这篇关于如何在Google Apps脚本中获取选定的表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆