【问题标题】:How to get the table width如何获取表格宽度
【发布时间】:2020-08-14 20:21:16
【问题描述】:

我想获取 Google 文档中表格的宽度。以下屏幕截图显示了一个演示文档。它只有一个表,其中一行只有一个单元格。通过单击插入 > 表格,然后单击插入具有单行和单个单元格的表格的选项来添加表格。表格插入后没有被操作。

在 Google Apps 脚本类表的类表中,它没有获取宽度的方法,类行也没有,但类单元格有 getWidth(),所以我尝试使用它,但它返回 @987654327 @。我是文档所有者,它存储在我的单元中,我使用的是旧的运行时 (Mozilla Rhino)、Chrome、一个 G Suite 帐户。该项目是通过单击工具 > 脚本编辑器从 Docs UI 创建的。

这是代码(项目不包含任何其他内容)

function myFunction() {
  const doc = DocumentApp.getActiveDocument();
  const body = doc.getBody();
  const tables = body.getTables();
  const table = tables[0];
  const row = table.getRow(0);
  const cell = row.getCell(0);
  const width = cell.getWidth();
  Logger.log(width);
}

代码是从脚本编辑器运行的。这是日志

我已经在问题跟踪器中搜索了 getWidth。返回了一些结果,但它们看起来都不相关。

我已经搜索过了。

Google Apps Script getWidth() for document table cell width returns null 虽然它看起来像是重复的,但它是关于插入图像的。另一方面,OP尝试了

var width = insertPlace.getParent().asParagraph().asTableCell().getWidth();

但这也没有用。当前的答案是获取从 Google Drive 插入的图像的宽度。

所以问题是如何获得表格宽度?

如果getWidth()有问题,是否有另一种方法可以找到表格宽度,不仅在表格使用默认宽度时,而且在它更小时?

【问题讨论】:

    标签: google-apps-script google-docs grid-layout


    【解决方案1】:

    这是录音

    ja...@google.com

    状态:无法修复(预期行为)

    你好, 谢谢你的报告。如果单元格的宽度没有改变,函数“getWidth”返回空值。您可以手动更改宽度或使用“setWidth”方法使其适应图像大小。 更多信息: https://developers.google.com/apps-script/reference/document/table-cell#setWidth(Number)

    du...@google.com

    状态:无法修复(预期行为)

    嗨,

    尽管没有记录所有这些,但新表的预期行为是为未设置的属性检索 null。如果您选择单元格并修改其格式(字体大小、斜体等),那么您将获得这些属性的值。

    对于单元格宽度,当创建一个新表格时,所有单元格都是“均匀分布的单元格”,这意味着它没有“固定宽度”,如果您修改单元格的宽度,它将变为固定宽度。如果修改整个表格的默认宽度,则所有单元格都会更改为固定宽度。 Google Doc API 的预期行为是仅返回具有固定宽度的单元格的宽度。

    我实现了以下解决方法,它将记录每个单元格的宽度和表格的总宽度(新表格的默认宽度为 450 磅)。

    解决方法:

    /**
     * Code written by du....@google.com
     * @see https://issuetracker.google.com/issues/143810853#comment2
     */
    function getTabeCellAttributes() {
      var fileId = '[FILE-ID]';
      var textInTableCell = "test";
      var body = DocumentApp.openById(fileId).getBody();  
    
      var tableRow = body.findText(textInTableCell).getElement().getParent().getParent().getParent().asTableRow();
      var evenlyDistributedCells = 0;
      var defaultTableWidth = 450;
      var totalWidth = 0;
     
      for(var i=0; i<tableRow.getNumChildren(); i++) {
        var tableCell = tableRow.getChild(i).asTableCell();
        var tableCellWidth = tableCell.getWidth();
       
        if(tableCellWidth == null) {
          evenlyDistributedCells++;
        }
        else {
          totalWidth += tableCellWidth;
          defaultTableWidth -= tableCellWidth;
          Logger.log("Width of cell number: " + (i+1) + " is: " + tableCellWidth)
        }
      }
     
      if (evenlyDistributedCells!=0) {
        var evenlyDistributedWidth = defaultTableWidth/evenlyDistributedCells;
        totalWidth += defaultTableWidth;
        Logger.log('There are ' + evenlyDistributedCells + ' evenly distributed cells with a width of: ' + evenlyDistributedWidth)
      }
      else {
        Logger.log("There are no evenly distributed cells, all cells have a fixed width.")
      }
     
      Logger.log('The total width of the table is: ' + totalWidth);
    }
    
    • 代码既不属于我,也不是我写的,只是来自 issuetracker 的引用。

    【讨论】:

    • 所以对于使用默认宽度的表格来说,唯一的办法就是计算“正文”的宽度(页面宽度-左边距-右边距),对吧?
    • @Rubén 可能是,但它不也取决于您正在创建的表吗?如果您创建一个 1x3 的表格,您可能需要对其进行划分。
    • 我正在寻找的是获取表格宽度。我使用了 Class Table Cell getWidth 因为 Class Table 没有那个方法。如果 Table Cell getWidth 返回 null,则对问题中提到的情况没有帮助。
    • @Rubén 链接的问题与代码issuetracker.google.com/issues/143810853#comment2有一个很好的链接
    【解决方案2】:

    感谢@TheMaster 提及问题(我无法找到它们)。下面是一种获取表格大小的非常简单的方法,该方法适用于将表格作为文档主体的子项的特定情况。

    function myFunction1() {
      const doc = DocumentApp.getActiveDocument();
      const body = doc.getBody();
      const attributes = body.getAttributes();
      const width = attributes[DocumentApp.Attribute.PAGE_WIDTH] - attributes[DocumentApp.Attribute.MARGIN_LEFT] - attributes[DocumentApp.Attribute.MARGIN_RIGHT];
      Logger.log(width);
    }
    
    

    我的默认页面大小是 Letter(宽度 = 8.5 英寸),边距是 1 英寸。

    记录的表格宽度为 468 磅(1 英寸 = 72 磅)=6.5 英寸,因此宽度是预期的。

    【讨论】:

      【解决方案3】:

      我相信你的目标如下。

      • 您想从使用 Google Apps 脚本创建为默认大小的表格中检索表格宽度。

      问题和解决方法:

      不幸的是,在当前阶段,没有任何方法可以从在 Google 文档服务和 Docs API 中创建为默认大小的表格中检索表格宽度。 https://stackoverflow.com/a/63420215https://stackoverflow.com/a/63421935 已经提到了这一点。所以在这个答案中,我想提出一个使用 Google Apps 脚本检索表格宽度的解决方法。

      在此解决方法中,我使用 Microsoft Word。此解决方法的流程如下。在此流程中,它假设已创建了与您的问题类似的 Google 文档。

      1. 使用 Drive API 将 Google 文档(DOCX 数据)转换为 Microsoft Word。
      2. 使用 Google Apps 脚本解析 DOCX 数据。
        • 解压转换后的 DOCX 数据时,可以将数据作为 XML 数据进行分析。幸运的是,在 Microsoft Docs 中,详细规范以 Open XML 的形式发布。因此在这种情况下,可以使用 Google Apps Script 的 XmlService 分析 XLSX、DOCX 和 PPTX 等 Microsoft Docs。我认为这种方法在其他情况下也很有用。
      3. 从 DOCX 数据中检索表格宽度。

      示例脚本:

      function myFunction() {
        const documentId = DocumentApp.getActiveDocument().getId();
        const url = "https://docs.google.com/feeds/download/documents/export/Export?exportFormat=docx&id=" + documentId;
        const blob = UrlFetchApp.fetch(url, {headers: {authorization: `Bearer ${ScriptApp.getOAuthToken()}`}}).getBlob().setContentType(MimeType.ZIP);
        const docx = Utilities.unzip(blob);
        const document = docx.filter(b => b.getName() == "word/document.xml");
        if (document.length == 0) return;
        const xml = document[0].getDataAsString();
        const root = XmlService.parse(xml).getRootElement();
        const n1 = root.getNamespace("w");
        const body = root.getChild("body", n1).getChildren("tbl", n1)
        const obj = body.map((e, i) => {
          const temp = {};
          const tblPr = e.getChild("tblPr", n1);
          if (tblPr) {
            const tblW = tblPr.getChild("tblW", n1);
            if (tblW) {
              const w = tblW.getAttribute("w", n1);
              if (w) {
                temp.tableWidth = Number(w.getValue()) / 20;  // Here, the unit of "dxa" is converted to "pt"
              }
            }
          }
          return temp;
        });
        if (obj.length > 0) console.log(obj);
      
        // DriveApp.getFiles()  // This is used for including the scope of `https://www.googleapis.com/auth/drive.readonly`.
      }
      

      结果:

      • 使用此脚本检索表时,将检索tableWidth: 451.3。在本例中,单位为pt
      • 结果数组的索引表示表的索引。例如,Google 文档中的第一个表是 0

      注意:

      • 作为上述脚本的确认,当使用DocumentApp.getActiveDocument().getBody().appendTable([[""]]).getCell(0, 0).setWidth(200) 的脚本创建表并使用上述示例脚本检索表时,我可以确认检索到tableWidth: 200。从这种情况来看,Google Document 中的表格大小与 DOCX 数据中的表格大小相同。

      参考资料:

      【讨论】:

      • @Rubén 欢迎。也谢谢你。我认为这种方法会导致各种情况的变通方法。作为使用此方法的其他方法,您可以在github.com/tanaikech/DocsServiceApp 看到它们
      猜你喜欢
      • 2011-02-26
      • 1970-01-01
      • 2019-08-15
      • 1970-01-01
      • 2012-12-10
      • 1970-01-01
      • 1970-01-01
      • 2021-08-04
      • 2013-05-04
      相关资源
      最近更新 更多