Force download excel file using PHPExcel

18,619

Solution 1

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

Solution 2

Clean the output

ob_end_clean();
$objWriter->save('php://output');
exit();
Share:
18,619

Related videos on Youtube

Supreet Totagi
Author by

Supreet Totagi

Updated on September 14, 2022

Comments

  • Supreet Totagi
    Supreet Totagi over 1 year

    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

  • Guilherme Nascimento
    Guilherme Nascimento over 10 years
    "Read" (open in browser) or "Download" (application/octet-stream)?
  • Supreet Totagi
    Supreet Totagi over 10 years
    Thanks for the answer @Mark. But I still get gibberish response.
  • Mark Baker
    Mark Baker over 10 years
    Use "view source" and look for any characters such as spaces or newlines at the beginning of that gibberish
  • Ashbay
    Ashbay almost 10 years
    I was having the exactly same issue ... The problem was I put a blank line at the beginning of my PHP file, and I guess the browser try to display this line and thus, the excel file. Removing the line make it work.