[SalesForce] Export Visualforce Page in Excel as .xlsx and not as a Web Page.

I'm writing a Visualforce page which downloads an Excel file onto the user's computer. I have done this by adding the following to the <apex:page> tag:
contentType="application/vnd.ms-excel#My File Name.xls" cache="true"

This successfully downloads a file which opens in Excel, however I get the error that the file format and extension don't match. This is because I am actually opening a Web Page in Excel. When I go to save it, I have to change the file type from Web Page to Excel Workbook.

Is there any way to automatically download the page as an Excel Workbook to avoid these two issues?

Thanks

Best Answer

The content of the page must be tabular format to be displayed as excel file.

You can make sure of that as follows

  • Remove the sfdc html/style coponents
    <apex:page standardStylesheets="false" showHeader="false"/>

  • Render data in tabular format (Use standard HTML tags, instead of apex:dataTable)
    e.g.,

    <table> <thead><tr><th>Header</th></tr></thead> <tbody><tr><td>Data</td></tr></tbody> </table>