Importing XLSX file from the monthly e-mail (in Gm

2019-08-01 02:00发布

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条回答
我命由我不由天
2楼-- · 2019-08-01 02:48
  • 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:

  1. Retrieve a blob of xlsx file.
  2. Convert xlsx format to Google Spreadsheet.
  3. Retrieve values from the converted Spreadsheet.
  4. Remove the converted file.
  5. 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.
    1. attachments[0] is the blob of xlsx file.
    2. About the xlsx file, the data you want to put is in a 1st tab.

Reference:

If I misunderstood your question and this didn't work, I apologzize.

查看更多
登录 后发表回答