Apps Script导出Google Sheet时输出旧版本内容该如何解决?
问题原因
Google Apps Script的Spreadsheet服务会对本地的表格写入操作做批量缓冲,所有你在Loop_through_Billing_List中完成的单元格修改操作,默认不会立刻同步到Google云端服务器,只是暂存在本地缓存中。此时调用云端导出接口拉取的始终是云端存储的旧版本数据,Utilities.sleep不会触发缓存提交,所以等待没有效果。就算你重新调用SpreadsheetApp.openById打开表格,读取的也是本地缓存的实例,不会触发云端同步。
解决方法
在完成所有表格写入操作之后、调用导出函数之前,添加SpreadsheetApp.flush()即可,这个方法会强制把所有本地暂存的变更同步到云端,确保导出接口拉取到最新的内容。
修改后的参考代码:
var bss = SpreadsheetApp.openById("the_ID"); var billing_sheet = bss.getSheets()[0]; function Main(){ Loop_through_Billing_List(); // 这个函数负责在Google Sheet中生成数据 // 新增此行,强制同步所有本地变更到云端 SpreadsheetApp.flush(); getGoogleSpreadsheetAsExcel(); // 导出Google Sheet为Excel并发送邮件 } function getGoogleSpreadsheetAsExcel(){ try { var attemp = SpreadsheetApp.openById("the_ID"); var url = "https://docs.google.com/feeds/download/spreadsheets/Export?key=" + attemp.getId() + "&exportFormat=xlsx"; var params = { method : "get", headers : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()}, muteHttpExceptions: true }; var blob = UrlFetchApp.fetch(url, params).getBlob(); blob.setName(bss.getName() + ".xlsx"); MailApp.sendEmail(requestor_email, "账单 " + FormatDate(date_start) + " - " + FormatDate(date_end), "附件中为生成的XLSX文件", {attachments: [blob]}); } catch (f) { Logger.log(f.toString()); } }
内容的提问来源于stack exchange,提问作者business
相关产品推荐
相关产品推荐

