Importing XLSX file from the monthly e-mail (in Gmail) to the designated Google Sheet

会有一股神秘感。 提交于 2019-12-31 04:22:18

问题


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:

  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:

  • 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!