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

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).

<?php

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(
           $myVariableCSV,
           200,
           [
		 //Defines the content of the query as an Excel file
             'Content-Type' => 'application/vnd.ms-excel',
		 //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!