[SalesForce] Warning when opening Apex generated Excel .xls

I am trying to send an E-Mail with an Excel Attachment. Everything works, except I am getting a warning when I am trying to open the send attachment:

The file format and extension of 'ExcelfileSC.xls' don't match. The file could be corrupted or unsafe. Unless you trust its source, don't open it. Do you want to open it anyway?

Here is the relevant part of my code:

Messaging.EmailFileAttachment attach = new Messaging.EmailFileAttachment();
attach.ContentType = 'application/vnd.ms-excel; charset=UTF-8';
blob excel = blob.valueOf('\uFEFF'+finalstr);
attach.setBody(excel);
attach.setFileName('ExcelfileSC.xls');

I am setting the right filename and contenttype, so why does the format + extension not match?

Best Answer

Excel is warning you that the internal structure of the file is not a real Excel Workbook format. The software is intelligent enough to recognize that it is something else (I presume you're rendering HTML/XML) and knows how to display/modify the contents, but the file itself is not an XLS file, which has specific headers and a binary format. It doesn't matter if ContentType and the file extension agree, this error is only concerned about the file's extension versus the actual contents of the file. As an example, if I hand you a file called "dancing-cats.gif", you open the file in a text editor, and you see a "JFIF" tag, you might realize that the file is not a GIF, but instead most likely a JPEG.

Related Topic