-1

Im trying to export my table player mysql to an excel file with phpspreadsheet. The problem is that when the file is downloaded, when we open the file, we have the html page in the file (with the excel content). Because of that, the file is corrupted. For sure is the return of the controller which doesn't work. But how to do?

Here is the controller:

* @Route("/export", name="doExport", methods={"POST"})
*/
public function export(Connection $conn, ExportExcel $exportExcel, TrainerRepository $trainerRepository, StaffRepository $staffRepository)
{

  $exportExcel->exportExcel($conn);


  return $this->render('Effectif/home.html.twig', [
   'trainers' => $trainerRepository->findBy(['id'=>228]),
   'staffs' => $staffRepository->findAll()
]);
   }

The image of the problem: enter image description here The complete code for export is here: http://pastebin.fr/61555

$filename = 'joueurs.xlsx';

header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'. $filename);
header('Cache-Control: max-age=0');
$Excel_writer->save('php://output');
    }
}

Please don't close the post.

dani45
  • 1
  • 3
  • the "secret" is, that there can only be one response to a request. thus, you can't both submit a file and a page. since you have `return $this->render(...)` after you already posted the file ... well, you get a corrupted file. however, there is a `return $this->file($fileLocation)` option in symfony. however, to achieve a download while returning a file is a bit more complex ... you have to load a page, which tries to redirect to a route that will return the file. – Jakumi Mar 20 '20 at 11:47

1 Answers1

0

this is working, in the controller:

 * @Route("/export", name="doExport", methods={"POST"})
 */
public function export(Connection $conn, ExportExcel $exportExcel, TrainerRepository $trainerRepository, StaffRepository $staffRepository)
{

  $targetPath = $exportExcel->exportExcel($conn);

   $response = new BinaryFileResponse($targetPath);
    return $response;

    }
}

In the service export:

$filename = 'joueurs.xlsx';

header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'. $filename);
header('Cache-Control: max-age=0');
$download_dir = '../var/downloads/';
$targetPath = $download_dir.$filename;
$Excel_writer->save($targetPath);
return $targetPath;
    }
}
?>
dani45
  • 1
  • 3