Download the excel file by using download option Please help me

I have used the phpspredsheet to generate the Excel file. but all works perfect but i want to browser donwload so i have set following code but the file generate the encode with buggy characters.

header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Cache-Control: max-age=0');
    $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');

output:: like �QĿi!��K�y3�J<���Z1�0?Y�L%zV

try this


I recomend the use of this lib for excel spredsheet file:

composer require box/spout


use Box\Spout\Writer\WriterFactory;
use Box\Spout\Common\Type;

    public function xlsxSpout($id = null) {
             $user = $this->Users->get($id);
             $fileName = 'spreadsheet.xlsx';
             $writer = WriterFactory::create(Type::XLSX); // for XLSX files
             //$writer = WriterFactory::create(Type::CSV); // for CSV files
             //$writer->openToFile($fullFilePath); // write data to a file or to a PHP stream
             $writer->openToBrowser($fileName); // stream data directly to the browser
             $writer->addRow(['ID', 'Name', 'Email']); // header
             $writer->addRow([$user->id, $user->name, $user->email]); // add a row at a time
             //$writer->addRows($rows); // add multiple rows at a time
             $this->autoRender = false;

I agree with @Diego . I also use box/spout for excel import and export which works nice.

I got the Solution for this Problem.well,
Don’t Need any third party lib for export the excel. same code as i mention above used but you can use the Ob_clean() method before export the code works fine.

you can refer below link for read,write and download excel file,