Symfony, Excel, CSV | Generating a CSV file for Excel with Symfony

Web developer Front-End in Oise, France - Gary Deshayes <--Traduction

Created at : Thursday 6 August 2020

It's a common practice on web applications to extract data via CSV, whether it's to retrieve statistics or to make data backups, I'll show you how this is easily done with Symfony via a Controller.

How to generate the CSV file with a Symfony Controller

To generate the file, it must be constructed as in the following example, by defining the columns of the CSV file with semicolons (;) and line breaks (\n).



namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class HomeController extends AbstractController
     * @Route("/home", name="home")
    public function home()
	//Column names in the first rows
    // the \n at the end allows you to do a super important line break in CSV
    // the semicolon separates the data into columns
	$myVariableCSV = "Lastname; Firstname; Age;\n";
	//Adding data (with the . in front to add the data to the existing variable)
	$myVariableCSV .= "John; Doe; 26;\n";
    //If you wish to add a space
    $myVariableCSV .= " ; ; ; \n";
    //Other data
	$myVariableCSV .= "Chuck; Norris; 80;\n";
	//We give the variable in string to the response, we set the HTTP code to 200
    return new Response(
		 //Defines the content of the query as an Excel file
             'Content-Type' => 'application/',
		 //We indicate that the file will be in attachment so opening the download box, as well as the definition of the name of the file
             "Content-disposition" => "attachment; filename=Tutoriel.csv"

CSV file recovery

When accessing the route /home as in the example, a file save window will allow you to retrieve the file.

You just have to open your CSV file with Excel or other software.

Preview of the file in Excel

Symfony, Excel, CSV | Generating a CSV file for Excel with Symfony

You can see that our columns are well defined, that we have the desired data in the right place with a line break in between.

You now know how to generate a CSV file with Symfony


Thank you for reading, feel free to share!

News publications :

Created at : Monday 1 November 2021

Javascript Framework JS

Created at : Sunday 31 October 2021


Created at : Wednesday 1 September 2021

Javascript Framework JS

Created at : Saturday 28 November 2020

Javascript SQL Framework JS

Created at : Sunday 20 September 2020


Created at : Thursday 6 August 2020

Javascript jQuery

Created at : Monday 23 March 2020


Created at : Friday 14 February 2020

Symfony Bugs

Created at : Sunday 26 January 2020