出于备份目的,我想使用以下脚本将Google电子表格转换为XLSX并将其发送到所选的电子邮件地址。几个星期前,这个脚本已用于我使用的一些电子表格。但是,从其他一些电子表格中,我收到的电子邮件中包含“破损”的附件。目前,我无法再次使用它,我怀疑代码存在兼容性问题。
有人可以帮帮我吗?
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("amit@labnol.org", "Google Sheet to Excel", "The XLSX file is attached", {attachments: [blob]});
} catch (f) {
Logger.log(f.toString());
}
}
附有“破损”附件的样本作为打印屏幕。它仍然以XLSX的形式出现,但它的HTML代码表明Document不存在。尽管如此,脚本生成的链接是正确的。当手动完成(将生成的链接复制/粘贴到浏览器中)时,它可以正常工作。
破碎的附件:
答案 0 :(得分:1)
我改用了下面的脚本。请务必启用Google Drive API 2(Ressources \ Advanced Google Services)
function myFunction(config) {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var spreadsheetId = spreadsheet.getId()
var file = Drive.Files.get(spreadsheetId);
var url = file.exportLinks[MimeType.MICROSOFT_EXCEL];
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
var fileName = (spreadsheet.getName()) + '.xlsx';
var blobs = [response.getBlob().setName(fileName)];
var receipient = "xxx"
var subject = "xxx"
var emailbody = "xxx"
MailApp.sendEmail(receipient, subject, emailbody, {attachments: blobs});
}
答案 1 :(得分:0)
我在@ roman77代码上遇到了一些问题,因为某些行似乎已被弃用。
经过一些修改,它现在可以工作。
function send_report_email(spreadsheetId) {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var spreadsheetId = spreadsheet.getId();
var file = DriveApp.getFileById(spreadsheetId);
var url = 'https://docs.google.com/spreadsheets/d/'+spreadsheetId+'/export?format=xlsx';
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
var fileName = (spreadsheet.getName()) + '.xlsx';
var blobs = [response.getBlob().setName(fileName)];
var receipient = "xxxx"
var subject = "xxxx"
var emailbody = "first line \n\nsecond line \n\nCheers!,"
MailApp.sendEmail(receipient, subject, emailbody, {attachments: blobs});
}