I\'m trying to import an xlsx file from a Gmail Attachment to Google Drive (as Google Sheet) using Google Apps Script. I\'ve tried using the Advanced Drive API in GAS, but doing
blob
of the attachment file is application/octet
.blob
is actually a XLSX file.blob
of application/octet
is used with Drive.Files.insert()
, an error of Invalid mime type provided
occurs.If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
blob
is application/octet
,
Drive.Files.insert({title: 'Converted Spreadsheet', parents: [{id: "root"}], mimeType: MimeType.GOOGLE_SHEETS}, blob, {convert: true})
is run, the error of Invalid mime type provided
occurs.Drive.Files.insert({title: 'Converted Spreadsheet', parents: [{id: "root"}]}, blob, {convert: true})
is run, no error occurs. But the mimeType of created file is application/octet
. By this, the file cannot be directly opened at Google Drive. In this case, it is required to change the mimeType of created file to XLSX. I think that the reason of this is due to This field can be left blank, and the mimetype will be determined from the uploaded content's MIME type.
. RefFrom above situation, in this answer, I would like to propose to set the mimeType of XLSX to blob
before Drive.Files.insert
is run.
When your script is modified, please modify as follows.
var blob =attachment
var blob = attachment.setContentType(MimeType.MICROSOFT_EXCEL); // MimeType.MICROSOFT_EXCEL or MimeType.MICROSOFT_EXCEL_LEGACY
or
If blob
has the filename with the extension, you can also use the following script. In this case, the mimeType is automatically given by the extension of the filename.
var blob = attachment.setContentTypeFromExtension();
mimeType: MimeType.GOOGLE_SHEETS
in file
.an xlsx file from a Gmail Attachment
. And you say the Gmail attachment is imported to Google Apps Script as application/octet instead of application/vnd.ms-excel
.
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.application/vnd.ms-excel
.If this didn't resolve your issue, I apologize.
These
parents: [{id: folderId}],
mimeType: MimeType.GOOGLE_SHEETS
refer to the input file. See docs here. You should skip these.
This snippet worked for me with Google Drive API v2:
function abc() {
var mail = GmailApp.search("SEARCH_TERM")[0];
var msg = mail.getMessages()[0];
var blob = msg.getAttachments()[0];
var file = {
title: 'Converted Spreadsheet'
};
Drive.Files.insert(file, blob, {convert: true});
}