从Google Apps脚本启动下载

tbkn23

我使用Google Apps脚本在电子表格中添加了一个新菜单项。该菜单项创建一个文件,但是我希望它在创建文件后启动文件下载。

这可能吗?

请记住,这不是Web应用程序,而是电子表格中的菜单项。

谢谢

编辑:

感谢Serge insas的建议,以下简单脚本可以完美运行,并打开包含所需链接的下载窗口:

function onOpen() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var csvMenuEntries = [ {name: "Zip all CSVs", functionName: "saveAsCSV"} ];
  ss.addMenu("CSV", csvMenuEntries);
};

function saveAsCSV() {
  var folder = createCSVs(); // creates a folder with CSV for each Sheet
  var zipFile = zipCSVs(folder, "DI.zip"); // creates a zip of all CSVs in folder

  var ui = UiApp.createApplication().setTitle("Download");
  var p = ui.createVerticalPanel();
  ui.add(p);
  p.add(ui.createAnchor("Download", zipFile.getDownloadUrl()));
  SpreadsheetApp.getActive().show(ui)
}
塞尔萨·萨萨斯

编辑:阅读下面的评论,Zig Mandel指出“复杂”版本的局限性是完全正确的,这确实是显示其他方法的简单(有趣)的练习。


我认为您必须使用中间Ui作为弹出窗口来确认下载。之后,我知道有2种可能的方法,一种非常简单,另一种非常繁琐,请自行选择,下面的代码显示了这两种方法。

注意:要使用复杂的应用程序,您需要部署您的应用程序(即保存版本并将其部署为webapp),对于简单的应用程序,只需“按原样”使用它即可。(我在代码注释中显示了简单的代码)。

代码 :

function onOpen() {
  var menuEntries = [ {name: "test download", functionName: "downloadFile"}
                     ];
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  sheet.addMenu("Utils",menuEntries);
}

function downloadFile(){
  var file = DriveApp.createFile('test file', 'Some content in this file to test it');
  var fileID = file.getId();
  var fileName = file.getName();
  var ui = UiApp.createApplication().setTitle('Download');
  var url = ScriptApp.getService().getUrl()+'?&ID='+fileID+'&name='+fileName;
  var p = ui.createVerticalPanel();
  ui.add(p);
  p.add(ui.createAnchor('click to download', url));
  p.add(ui.createAnchor('or use this link ',file.getDownloadUrl()));// this is the simple one, just get the file you created and use getDownloadUrl()
  SpreadsheetApp.getActive().show(ui)
}

function doGet(e){
  var fileId = e.parameter.ID;
  var fileName = e.parameter.name;
  var fileString = DocsList.getFileById(fileId).getContentAsString();
  return ContentService.createTextOutput(fileString).downloadAsFile(fileName);
}

PS:我写这篇文章很有趣,“复杂版本”真的很有趣,恕我直言:-)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章