Force download excel file using PHPExcel

http, http-headers, php, phpexcel

Solution

Wrong Content Type and Filetype won't help:

`application/vnd.ms-excel` is for `.xls` files created with the `Excel5` Writer

`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet` is used for `.xlsx` files created with the `Excel2007` Writer

But if you're seeing that `gibberish` (which is actually the xlsx file itself) in the browser, then the chances are that you're echoing or printing something else to the browser as well, even if it's only a whitespace character like a space, tab or newline before you send those headers

Problem

I'm using following headers to output excel sheet generated through PHPExcel: ``` // Redirect output to a client’s web browser (Excel2007) header('Content-Type: application/vnd.ms-excel'); header('Content-Disposition: attachment;filename="01simple.xlsx"'); header('Cache-Control: max-age=0'); $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007'); $objWriter->save('php://output'); ``` Instead gibberish text is sent to the browser: ``` PK������&DG�D�X��������[Content_Types].xml��MN�0���"�%nY ��vAa �(0����ؖg�w{&i�@�nbE�{��y��d۸l m�����X�(���)���F��;@1_�����c)j�x/%��E��y� ``` Could anyone help me with proper headers to force download an excel file? Many thanks. Edit 1: ``` header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header('Content-Disposition: attachment;filename="01simple.xlsx"'); header('Cache-Control: max-age=0'); $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007'); $objWriter->save('php://output'); ``` Still not working

Original source