首页 > 解决方案 > 将 Google 表格转换为 Excel,然后作为电子邮件附件发送,但无法访问 XLXS 文件(未经授权的错误 401)

问题描述

下面的代码可以将谷歌表格转换为 excel 文件并通过电子邮件发送,但该文件没有实际的 excel,只有未经授权的错误 401。

function getGoogleSpreadsheetAsExcel(){

try { var ss = SpreadsheetApp.getActive();

var url = "https://docs.google.com/feeds/download/spreadsheets/Export?key=" + ss.getId() + "&exportFormat=xlsx";

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("Horgstar1212@gmail.com", "Google Sheet to Excel", "The XLSX file is  attached", {attachments: [blob]});}

catch (f) {
  Logger.log(f.toString()); }
}

我相信这与访问文件的授权有关,但我对编码和 API 非常陌生,因此将不胜感激。

标签: excelapigoogle-apps-scriptgoogle-sheets

解决方案


问题:

你的代码对我来说很好。

根据您收到的错误消息,您必须遇到一些授权问题,并基于此确保清单文件中包含以下电子表格和文档范围:

"oauthScopes": ["https://www.googleapis.com/auth/script.external_request",
    "https://www.googleapis.com/auth/documents",
    "https://www.googleapis.com/auth/spreadsheets"]

appsscript.json应该是这样的:

{
  "timeZone": "Europe/Paris",
  "dependencies": {
  },
  "exceptionLogging": "STACKDRIVER",
  "runtimeVersion": "V8",
  "oauthScopes": ["https://www.googleapis.com/auth/script.external_request",
    "https://www.googleapis.com/auth/documents",
    "https://www.googleapis.com/auth/spreadsheets"]
}

虽然我发布了生成和发送 excel 文件的推荐方法。

推荐方法:

function myFunction() {
const ss = SpreadsheetApp.getActive();
const nameFile = ss.getName() + ".xlsx";
const requestData = {"method": "GET", "headers":{"Authorization":"Bearer "+ScriptApp.getOAuthToken()}};  
const url = "https://docs.google.com/spreadsheets/d/"+ ss.getId() + "/export?format=xlsx";
const result = UrlFetchApp.fetch(url , requestData);  
const contents = result.getContent();
    
MailApp.sendEmail("Horgstar1212@gmail.com", 
                  "Google Sheet to Excel",
                   "The XLSX file is  attached", 
                  {attachments:[{fileName:nameFile, content:contents, mimeType:"MICROSOFT_EXCEL"}]});     
}

推荐阅读