首页 > 解决方案 > 添加大量表时如何解决错误

问题描述

我有这个谷歌脚本,我正在使用另一个文档中的模板表创建一个文档。

新文档中将包含许多小表格(如卡片)。下面的代码适用于 100、200 个表,并且在不到 10 秒内完成。但是对于超过 500 个表它失败了。“执行”窗口中没有错误消息。

我已经尝试了 saveAndClose() 函数(已注释掉),但错误仍在继续,运行时间更长。

我没有办法解决这个问题。任何帮助或想法将不胜感激。


function insertSpecification_withSection(){
  startTime = new Date()
  console.log("Starting Function... "); 
  
  // Retuns a Table Template Copied from another Document
  reqTableItem = RequirementTemplate_Copy();
  
  
  // Creates X number of separated tables from the template
  for (var i = 0; i < 500; i++){
    table = DocumentApp.getActiveDocument().getBody().appendTable(reqTableItem.copy());

    //    if((i % 100) === 0) {
    //      DocumentApp.getActiveDocument().saveAndClose();
    //    }
    //    
    
  }
  endTime = new Date();
  timeDiff = endTime - startTime;
  console.log("Ending Function..."+ timeDiff + " ms"); 
  
}

function RequirementTemplate_Copy() {

  //---------------------------------------------------------------------------------------------------------------------------------------------------
  var ReqTableID = PropertiesService.getDocumentProperties().getProperty('ReqTableID');
  try{
    var templatedoc = DocumentApp.openById(ReqTableID);
  } catch (error) {
    DocumentApp.getUi().alert("Could not find the document. Confirm it was not deleted and that anyone have read access with the link.");
    //Logger.log("Document not accessible", ReqTableID)
  } 
  var reqTableItem = templatedoc.getChild(1).copy();
  //---------------------------------------------------------------------------------------------------------------------------------------------------
  return reqTableItem
}

标签: google-apps-scriptgoogle-docs

解决方案


就像在另一个答案中提到的那样,最好将文档保存在循环之外并在需要时调用它。文档的正文也是如此。

let currentDoc = DocumentApp.getActiveDocument();
let bodyDoc = currentDoc.getBody();
for (var i = 0; i < 500; i++){
    table = bodyDoc.appendTable(reqTableItem.copy());
    //    if((i % 100) === 0) {
    //      currentDoc.saveAndClose();
    //    }
    //    
  }

但是,由于您提到您收到Exception: Service Documents failed while accessing document with id错误,您可能需要在问题跟踪器上查看此问题,因为您遇到的可能是Apps 脚本的错误。

如果是这种情况,我建议您为该问题加注星标并最终添加一条评论,说明您受到它的影响。

参考


推荐阅读