如何获取表格宽度 结果:注意:

问题描述

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

在Google Apps脚本类表的类表中,它既没有获取宽度的方法,也没有类行,但是类单元格有getWidth(),所以我尝试使用它,但是它返回null。我是文档所有者,它存储在“我的单位”中,我使用的是旧版运行时(Mozilla Rhino),Chrome和G Suite帐户。该项目是通过在Google文档用户界面中依次点击工具>脚本编辑器创建的。

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

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云端硬盘插入图片的宽度。

所以问题是如何获取表格宽度?@H_502_34@

如果getWidth()有问题,是否有另一种方法来查找表格宽度,不仅是在表格使用认宽度时,还是在表格较小时?

解决方法

这是一个录音

ja ... @ google.com

状态:无法解决(预期行为)

你好, 感谢您的举报。如果单元格的宽度未更改,则函数“ getWidth”返回null。您可以手动更改宽度,也可以使用“ setWidth”方法使其适应图像尺寸。 更多信息: https://developers.google.com/apps-script/reference/document/table-cell#setWidth(Number)

du ... @ google.com

状态:无法解决(预期行为)

嗨,

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

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

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

解决方法:

/**
 * Code written by [email protected]
 * @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引用问题(我无法找到它们)。下面是获取表大小的一种非常简单的方法,该表适用于将表作为文档正文的子项的特定情况。

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英寸,因此该宽度是预期的。

,

我相信您的目标如下。

  • 您要使用Google Apps脚本从作为默认尺寸创建的表格中检索表格宽度。

问题和解决方法:

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

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

  1. 使用云端硬盘API将Google文档(DOCX数据)转换为Microsoft Word。
  2. 使用Google Apps脚本解析DOCX数据。
    • 解压缩转换后的DOCX数据时,可以将其分析为XML数据。幸运的是,在Microsoft Docs,详细规范以Open XML的形式发布。因此,在这种情况下,可以使用Google Apps脚本的XmlService分析Microsoft文档(例如XLSX,DOCX和PPTX)。我认为这种方法在其他情况下也很有用。
  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文档中的表大小与DOCX数据中的表大小相同。

参考文献: