많은 수의 테이블을 추가 할 때 오류를 해결하는 방법
다른 문서에있는 템플릿 테이블을 사용하여 문서를 만드는이 Google 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
}
답변
긴 메서드 체인을 사용하여 for
루프 내부에 테이블을 추가하는 대신 문서 본문에 대한 변수를 앞에 선언 for
하고 for
. 다시 말해,
바꾸다
// Creates X number of separated tables from the template
for (var i = 0; i < 500; i++){
table = DocumentApp.getActiveDocument().getBody().appendTable(reqTableItem.copy());
으로
var body = DocumentApp.getActiveDocument().getBody();
// Creates X number of separated tables from the template
for (var i = 0; i < 500; i++){
table = body.appendTable(reqTableItem.copy());
위의 코드는 다음 템플릿으로 테스트되었습니다.

스크립트가 오류없이 완료되었습니다. 결과 문서에는 50 페이지가 있습니다.

다른 답변에서 언급했듯이 문서를 루프 외부에 저장하고 필요할 때 호출하는 것이 가장 좋습니다. 문서의 본문도 마찬가지입니다.
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 Script 의 버그 일 수 있으므로 Issue Tracker 에서이 문제 를 살펴 보는 것이 좋습니다 .
이 경우 문제에 별표를 표시하고 결국 영향을 받는다는 의견을 추가하는 것이 좋습니다.
참고
- Apps Script 권장 사항 .