将.xlsm文件传输到GSheet时,Google Apps脚本错误“错误请求”

问题描述 投票:0回答:1

我的收件箱中有一个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. 
google-apps-script google-sheets gmail email-attachments xlsm
1个回答
0
投票

我相信您的目标如下。

  • 您要将.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。
  • 当通过Drive API 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更改为MimeType.MICROSOFT_EXCEL,可以将.xlsm文件转换为Google Spreadsheet。

参考:

© www.soinside.com 2019 - 2024. All rights reserved.