Symfony return a response to export excel

excel, symfony

Solution

Controller must return an instance of `Response` class, so do the following:

ob_start();
$objWriter->save('php://output');

return new Response(
    ob_get_clean(),  // read from output buffer
    200,
    array(
        'Content-Type' => 'application/vnd.ms-excel',
        'Content-Disposition' => 'attachment; filename="doc.xls"',
    )
);

If you use Excel 2007 or upper set content type to `"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"` and file extension to `xlsx`.

Problem

How do I return a response in Symfony that will output an excel file? I am getting an error that I must return a response and it needs to be in a string correct? Help! ``` $excel = new PHPExcel(); $excel->setActiveSheetIndex(0); $excel->getActiveSheet() ->setCellValue('A1', 'hi'); $objWriter = \PHPExcel_IOFactory::createWriter($excel, 'Excel2007'); $objWriter->save(str_replace('.php', '.xlsx', __FILE__)); return $objWriter; ``` Error: The controller must return a response (Object(PHPExcel_Writer_Excel2007) given).

Original source