Google脚本xls附件未显示

时间:2017-03-24 12:52:59

标签: javascript google-apps-script google-api google-apps

有关为什么此脚本通过电子邮件发送附件但附件不是正确的电子表格的任何想法,并且看起来像某种谷歌错误页面。

enter image description here

function getGoogleSpreadsheetAsExcel(){
  
  try {
    
    var ss = SpreadsheetApp.getActive();
    
    var url = "https://docs.google.com/feeds/download/spreadsheets/Export?key=" + ss.getId() + "&exportFormat=xlsx";
    Logger.log(url);
    
    var params = {
      method      : "get",
      headers     : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
      muteHttpExceptions: true
    };
    
    var blob = UrlFetchApp.fetch(url, params).getBlob();
    
    blob.setName(ss.getName() + ".xlsx");
    
    MailApp.sendEmail("youremail@email.com", "Google Sheet to Excel", "The XLSX file is attached", {attachments: [blob]});
    
  } catch (f) {
    Logger.log(f.toString());
  }
}

2 个答案:

答案 0 :(得分:1)

我猜API已经改变了。您可以尝试使用Drive REST API(v3)。取代

var url = "https://docs.google.com/feeds/download/spreadsheets/Export?key=" + ss.getId() + "&exportFormat=xlsx";
var params = { ... };
var blob = UrlFetchApp.fetch(url, params).getBlob();

var url = "https://www.googleapis.com/drive/v3/files/" + ss.getId() + 
  "/export?mimeType=application/vnd.openxmlformats-officedocument.spreadsheetml.sheet&key=" +
  "{your API key}";
var blob = UrlFetchApp.fetch(url).getBlob();

我测试过并且有效。当然,您首先应该在API Manager获取自己的API密钥等。然后,您可以在APIs Explorer尝试一些API,例如简单的GET请求。或者您可以尝试使用某些API,在这种情况下Files: export,也可以在the documentation page itself,但请注意,您无法在此处尝试自己的API密钥。

答案 1 :(得分:1)

这是@sangbok帮助的更新代码:

{{1}}