如何加快功能将1张PDF格式保存到Google表格中的Google云端硬盘文件夹?

时间:2018-03-23 16:46:19

标签: google-apps-script

以下代码可以很好地将我的Google表格文件的“PO模板”表格以PDF格式保存到指定的Google云端硬盘文件夹“Purchase_Orders”。唯一的问题是该功能需要10秒以上才能运行。代码中是否有可以压缩的东西来加速这个脚本运行过程?

function checkSheet() {
  var sheetName = "POTemplate";
  var folderID = "Purchase_Orders";
  var sourceSpreadsheet = SpreadsheetApp.getActive();
  var sourceSheet = sourceSpreadsheet.getSheetByName(sheetName);
  var poNo = sourceSheet.getRange("G5").getValue();
  var shipTo = sourceSheet.getRange("E9").getValue();
  var pdfName = shipTo + " Purchase Order " + poNo;
  var folder = DriveApp.getFoldersByName(folderID);
  var destSpreadsheet = SpreadsheetApp.open(DriveApp.getFileById(sourceSpreadsheet.getId()).makeCopy(folder));
   var source = destSpreadsheet.getSheetByName(sheetName).getDataRange();
   source.copyTo(source, {contentsOnly: true});
  var sheets = destSpreadsheet.getSheets();
   for (i = 0; i < sheets.length; i++) {
   if (sheets[i].getSheetName() != sheetName){
     destSpreadsheet.deleteSheet(sheets[i])}}; 
  var theBlob = 
destSpreadsheet.getBlob().getAs('application/pdf').setName(pdfName);
  var newFile = folder.next().createFile(theBlob);
  DriveApp.getFileById(destSpreadsheet.getId()).setTrashed(true);
  var strUrl = newFile.getUrl()
  var html = HtmlService.createTemplateFromFile("NewTab");
  html.strUrl = strUrl
  SpreadsheetApp.getUi().showModelessDialog(html.evaluate(), 
"Congratulations!  "+ pdfName + " is now saved.")
}

1 个答案:

答案 0 :(得分:0)

我的代码有执行记录。

enter image description here

似乎File.makeCopy占用了50%的时间。 Folder.createFile也需要15%。

这意味着您的优化将来会很少。