问题
I receive an XLSX file from our client on regular basis, and I would like to automate the process of importing it from Gmail (it's automatically labeled) into Google Sheets. So far I managed to make it work for CSV files, but XLSX files seem to be trickier. Can someone help to adjust this code I have for CSV files?
function getCSV()
{
var thread = GmailApp.getUserLabelByName(‘Reconciliation’).getThreads(0,1);
var messages = thread[0].getMessages();
var len = messages.length;
var message=messages[len-1] //get last message
var attachments = message.getAttachments(); // Get attachment of first message
var csv = attachments[0].getDataAsString();
var data = Utilities.parseCsv(csv);
var sheet = SpreadsheetApp.openById("some id").getSheetByName(‘Data’);
sheet.clearContents();
var range = sheet.getRange(1, 1, data.length, data[0].length);
range.setValues(data);
}
回答1:
- You want to put the data from xlsx file attached to an email to the existing Spreadsheet.
If my understanding is correct, how about this modification? Please think of this as just one of several answers.
When you use this script, please enable Drive API at Advanced Google Services and API console. You can see about this at here.
Flow of modified script:
- Retrieve a blob of xlsx file.
- Convert xlsx format to Google Spreadsheet.
- Retrieve values from the converted Spreadsheet.
- Remove the converted file.
- Put the values to the sheet of
Data
in the existing Spreadsheet.
Modified script:
Please modify as follows.
From:var csv = attachments[0].getDataAsString();
var data = Utilities.parseCsv(csv);
To:
var xlsxBlob = attachments[0]; // Is supposes that attachments[0] is the blob of xlsx file.
var convertedSpreadsheetId = Drive.Files.insert({mimeType: MimeType.GOOGLE_SHEETS}, xlsxBlob).id;
var sheet = SpreadsheetApp.openById(convertedSpreadsheetId).getSheets()[0]; // There is the data in 1st tab.
var data = sheet.getDataRange().getValues();
Drive.Files.remove(convertedSpreadsheetId); // Remove the converted file.
Note:
- In this modification, it supposes the following points. If your situation is different from the following points, please modify it.
attachments[0]
is the blob of xlsx file.- About the xlsx file, the data you want to put is in a 1st tab.
Reference:
- Files: insert of Drive API v2
If I misunderstood your question and this didn't work, I apologzize.
来源:https://stackoverflow.com/questions/55494934/importing-xlsx-file-from-the-monthly-e-mail-in-gmail-to-the-designated-google