我创建了一个将电子表格(工作表)作为 PDF 保存到指定文件夹的函数。该功能运行良好,但是当我多次运行它时(我需要执行 20 次),在第 7、8 或 9 次运行后出现错误。错误是 429。它没有给我很多信息,我似乎无法找到错误是什么以及如何纠正。我已经尝试添加一个 Utilities.sleep(xxx) 并且当我进行 5 秒睡眠时它确实有效(但当它少于 5 秒时则不行)!
这是我的代码(使用 Utilities.sleep):
/**
* Creates a PDF file
*
* 2019-12-17 Simon: Created
*
* @param {?} token ScriptApp.getOAuthToken();
* @param {?} spreadsheet Spreadsheet (SpreadsheetApp.getActiveSpreadsheet())
* @param {string} sheetName Name of the sheet to print
* @param {string} pdfName Name of the pdf file (excluding .pdf)
* @param {string} folder Folder to save in
* @param {string} portrait true=portrait, false=landscape
* @param {number} scale 1 = Normal 100% -- 2 = Fit to width -- 3 = Fit to height -- 4 = Fit to Page
* @param {number} margins In inches. Dot as decimal separator, e.g. '0.2'
* @param {string} range Optional. E.g. 'D4:AX74'
*/
function savePdf(spreadsheet, sheetName, pdfName, folder, portrait, scale, margins, range) {
var rangeUse = (range ? '&range=' + range : '');
var sheetId = spreadsheet.getSheetByName(sheetName).getSheetId();
var url_base = spreadsheetId.getUrl().replace(/edit$/,'');
var url_ext = 'export?'
+ '&gid=' + sheetId
+ rangeUse
+ '&format=pdf' // export format
+ '&size=a4' // A3/A4/A5/B4/B5/letter/tabloid/legal/statement/executive/folio
+ '&portrait=' + portrait // true = Potrait / false= Landscape
+ '&scale=' + scale // 1 = Normal 100% -- 2 = Fit to width -- 3 = Fit to height -- 4 = Fit to Page
+ '&top_margin=' + margins // all four margins must be set!
+ '&bottom_margin=' + margins // all four margins must be set!
+ '&left_margin=' + margins // all four margins must be set!
+ '&right_margin=' + margins // all four margins must be set!
+ '&gridlines=false' // true/false
+ '&printnotes=false' // true/false
+ '&pageorder=2' // 1 = Down, then over -- 2 = Over, then down
+ '&horizontal_alignment=CENTER' // LEFT/CENTER/RIGHT
+ '&vertical_alignment=MIDDLE' // TOP/MIDDLE/BOTTOM
+ '&printtitle=false' // print title --true/false
+ '&sheetnames=false' // print sheet names -- true/false
+ '&fzr=true' // repeat row headers (frozen rows) on each page -- true/false
+ '&fzc=true' // repeat column headers (frozen columns) on each page -- true/false
+ '&attachment=false' // true/false
var token = ScriptApp.getOAuthToken();
var url_options = {headers: {'Authorization': 'Bearer ' + token, 'muteHttpExceptions': true,}};
Utilities.sleep(5000);
var response = UrlFetchApp.fetch(url_base + url_ext, url_options);
var blob = response.getBlob().getAs('application/pdf').setName(pdfName + '.pdf');
folder.createFile(blob);
}