允许用户命名要下载的文件

时间:2018-04-02 20:10:15

标签: google-apps-script google-sheets

我有一个链接,允许用户在Google电子表格中下载特定工作表的CSV格式版本。

var ssID = SpreadsheetApp.getActiveSpreadsheet().getId() + "&gid=" + SpreadsheetApp.getActiveSpreadsheet().getSheetByName('SheetName').getSheetId();
var url = "https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key=" + ssID + "&exportFormat=csv"; 

问题是下载的CSV文件名为“SpreadsheetName - SheetName”,这并不理想。有没有办法将其更改为用户如何命名下载的CSV文件?

1 个答案:

答案 0 :(得分:0)

一种方法是ContentService,与网络应用功能配对(即doPost(e)doGet(e))。事件对象将包含useful information,例如您所需的输出文件名和要输出的表格,如果您将其添加到脚本网址,例如https://script.google.com/......./exec?fileName=somename&sheets=Sheet1,Sheet2....

示例功能:

function doGet(eventObject) {
  if(!eventObject) throw new Error("You called this from the script editor.");
  else console.log(eventObject); // View the event object on Stackdriver.

  // Arrays of named URL parameters.
  var params = eventObject.parameters; 
  var output = ContentService.createTextOutput();
  // Assumes the url contains a named 'sheets' parameter.
  params.sheets.forEach(function (sheetName) {
    /* your code that gets data from each sheet with the given
       name and converts it into a CSV-formatted string. */
    output.append(thatDataStringYouGot);
  });
    // Assumes the url contains a named "fileName" parameter.
  output.setMimetype(MimeType.CSV).downloadAsFile(eventObject.parameter.fileName);
  return output;
}