excel - 将 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 非常陌生,因此将不胜感激。
解决方案
问题:
你的代码对我来说很好。
根据您收到的错误消息,您必须遇到一些授权问题,并基于此确保在清单文件中包含以下电子表格和文档范围:
"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"}]});
}
推荐阅读
- tensorflow - keras中的交叉熵损失计算错误
- php - 是否有一个 python 函数可以为 php.hash 获得相同的结果?
- python - Numpy:如何最好地对齐两个排序数组?
- sql - 识别缺失的行并在 SQL 中计算它们
- javascript - 从 Vue.js 中的子组件更新父组件
- c++ - 如何声明 std::chrono::duration
c++中的变量 - angular - 使用 @angular/fire/auth 登录会导致 localhost 出现 403 错误
- machine-learning - 如何在目标具有多标签的多分类问题中使用 lightGBM
- ios - 如何对特定于语言环境的本地通知进行单元测试
- c# - XAML - Blend 不支持 Base64 ImageSource