google-apps-script - 添加大量表时如何解决错误
问题描述
我有这个谷歌脚本,我正在使用另一个文档中的模板表创建一个文档。
新文档中将包含许多小表格(如卡片)。下面的代码适用于 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
}
解决方案
就像在另一个答案中提到的那样,最好将文档保存在循环之外并在需要时调用它。文档的正文也是如此。
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 脚本的错误。
如果是这种情况,我建议您为该问题加注星标并最终添加一条评论,说明您受到它的影响。
参考
推荐阅读
- git - Git:通过 HTTP(s) 协议确认给定的提交是否存在
- amazon-web-services - AWS lex 可以接受附件吗?
- batch-file - 为什么 /i 选项不能与 xcopy 命令一起使用?
- python - PRAW/Tweepy 过滤关键字
- laravel - 在 laravel 中更改所有图像的 url 和链接 href
- oracle11g - 如何通过顶点中的动态操作在区域中没有日期时隐藏区域
- css - NativeScript Playground - 未应用内置类
- c# - 打开 id 未重定向到正确的登录页面
- amazon-web-services - 无服务器框架 lambda 执行角色不匹配?
- android - 动态添加视图后,按钮 onClick 不会触发