如何获得 table 宽度

How to get the table width

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

在 Class Table 来自 Google Apps Script Class Table 它没有获取宽度的方法, Class 行,但 Class 单元格有 getWidth(),所以我尝试使用它,但它 returns null。我是文档所有者,它存储在我的单元中,我使用的是旧的 运行time (Mozilla Rhino),Chrome,一个 G Suite 帐户。该项目是通过单击工具 > 脚本编辑器从文档 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。返回了一些结果,但其中 none 看起来是相关的。

我已经搜索过了。

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

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

但这也没有用。当前的答案是关于获取从 Google 驱动器插入的图像的宽度。

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

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

这是一个记录

ja...@google.com

Status: Won't Fix (Intended Behavior)

Hello, Thanks for your report. The function "getWidth" returns null if the cell's width hasn't changed. You can manually change the width or use the "setWidth" method to adapt it to the image size. More information: https://developers.google.com/apps-script/reference/document/table-cell#setWidth(Number)

du...@google.com

Status: Won't Fix (Intended Behavior)

Hi,

Despite all this not being documented, the intended behavior for a new table is to retrieve null for the attributes that aren't set. If you select the cell and modify its formatting (font size, italic, etc), then you'll get the values for those attributes.

For the cell width, when a new table is created all cells comes as “evenly distributed cells”, meaning it doesn’t have a “fixed width”, if you modify the width of a cell it’ll change to a fixed width. If you modify the default width of the entire table, all cells will change to a fixed width. The intended behavior for Google Doc API is to return the width only for cells with a fixed width.

I implemented the following workaround that will log you the width of each cell and the total width of the table (the default width for a new table is 450 points).

Workaround:

/**
 * 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的引用。

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

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 英寸。

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

我相信你的目标如下。

  • 您想从使用 Google Apps 脚本创建为默认尺寸的 table 中检索 table 宽度。

问题和解决方法:

不幸的是,在当前阶段,没有方法可以从 table 中检索 table 宽度,该 table 在 Google 文档服务和文档 [=67] 中创建为默认大小=]. and 已经提到了这一点。因此,在这个答案中,我想提出一种使用 Google Apps 脚本检索 table 宽度的解决方法。

在此解决方法中,我使用 Microsoft Word。此解决方法的流程如下。在此流程中,假设已经创建了一个 Google 像您的问题一样的文档。

  1. 使用驱动器 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 数据中检索 table 宽度。

示例脚本:

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`.
}

结果:

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

注:

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

参考文献: