我的收件箱中有一个Excel文件(.xlsm)作为Gmail附件,并希望将其传输到GDrive。在那里应该将其另存为GSheet。我正在尝试使用Apps脚本自动执行此过程。
[不幸的是,启动脚本时出现错误。 (对drive.files.insert的API调用失败,并出现错误:错误的请求)这很奇怪,因为脚本可以运行几次,并且可以毫无问题地转换文件。上周,它在我将带有附件的邮件转发给某人后就起作用了(不要问我上下文是什么)。但是现在,这都是历史,我不知道如何解决该错误。
我是StackOverflow的新手,我非常期待您的每一个答复。非常感谢。
这里是代码:
function importFunction() {
var threads = GmailApp.search('CC520_Report_Lukas_GAS_ABC');
var messages = threads[0].getMessages();
var message = messages[0];
var attachment = message.getAttachments()[0];
var resource = {
title: 'NewFileLukas',
mimeType: MimeType.GOOGLE_SHEETS,
parents: [{id: 'xxxxx6BD1SIfI0Cz5bmGahzSlHUxxxxxx'}],
};
var insert = Drive.Files.insert(resource, attachment); // Here comes the error.
我相信您的目标如下。
.xlsm
文件转换为Google Spreadsheet。attachment
您正在使用的是.xlsm
文件。API call to drive.files.insert failed with error: Bad Request
发生错误Drive.Files.insert(resource, attachment)
。为此,这个答案怎么样?我也遇到过同样的问题。
.xlsm
文件的mimeType为application/vnd.ms-excel.sheet.macroenabled.12
。在您的脚本中,使用console.log(attachment.getContentType())
时,如果attachment
是.xlsm
文件,则将返回此类mimeType。importFormats
中的“关于:获取”方法确认Ref时,似乎application/vnd.ms-excel.sheet.macroenabled.12
可以转换为application/vnd.google-apps.spreadsheet
。可以在Drive API v2和v3中看到。application/vnd.ms-excel.sheet.macroenabled.12
数据用于Drive.Files.insert(resource, attachment)
时,会发生错误。在这种情况下,我确认即使使用Drive API v3进行了测试,也会出现相同的问题。因此,作为当前解决方法,我建议通过更改Blob的mimeType将.xlsm
文件转换为Google Spreadsheet。
修改脚本后,请进行如下修改。
从:var attachment = message.getAttachments()[0];
至:var attachment = message.getAttachments()[0].setContentType(MimeType.MICROSOFT_EXCEL);
或
var attachment = message.getAttachments()[0];
if (attachment.getContentType() == "application/vnd.ms-excel.sheet.macroenabled.12") {
attachment.setContentType(MimeType.MICROSOFT_EXCEL);
}
MimeType.MICROSOFT_EXCEL
,可以将.xlsm
文件转换为Google Spreadsheet。