google-apps-scriptgoogle-sheetsgmailemail-attachmentsxlsm

Google Apps Script error 'Bad Request' when transferring a .xlsm-file to a GSheet


I have an Excel-File (.xlsm) as a Gmail-attachment in my inbox and want to transmit it to GDrive. There it should be saved as a GSheet. I am trying to automatize this process using Apps Script.

Unfortunately, I get an error starting the Script. (API call to drive.files.insert failed with error: Bad Request) It's very strange because a few times the script works and the file could be converted without any problems. Last week, it worked as soon as I forwarded the Mail with the attachment to someone (Don't ask me where's the context). But now, it's all history and I don't know how to fix the error.

I am new on StackOverflow and I am really looking forward to every answer from you. Thank you very much.

Here's the code:

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. 

Solution

  • I believe your goal as follows.

    For this, how about this answer? I had also experienced the same issue.

    Modification points:

    So as the current workaround, I would like to propose to convert the .xlsm file to Google Spreadsheet by changing the mimeType of the blob.

    Modified script:

    When your script is modified, please modify as follows.

    From:
    var attachment = message.getAttachments()[0];
    
    To:
    var attachment = message.getAttachments()[0].setContentType(MimeType.MICROSOFT_EXCEL);
    

    or

    var attachment = message.getAttachments()[0];
    if (attachment.getContentType() == "application/vnd.ms-excel.sheet.macroenabled.12") {
      attachment.setContentType(MimeType.MICROSOFT_EXCEL);
    }
    

    Note:

    Reference: