Laravel export data to Excel/CSV

Mohit Mehta
1 min readMar 1, 2019

Many times we need data to be exported in CSV or Excel file. There are many packages available to export data but we can also do this by few lines of code.

Export data in Excel file

$headers = [
'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
'Content-type' => 'application/vnd.ms-excel',
'Content-Disposition' => 'attachment; filename=file_name.xlsx',
'Expires' => '0',
'Pragma' => 'public'
];
$list = TableModel::all()->toArray();# add headers for each column in the CSV download
array_unshift($list, array_keys($list[0]));
$callback = function() use ($list) {
$FH = fopen('php://output', 'w');
foreach ($list as $row) {
fputcsv($FH, $row);
}
fclose($FH);
};
return Response::stream($callback, 200, $headers);

Here I have fetched data from model TableModel and convert it to array. We can use any type of array here. Above code will export data in Excel file. If you want CSV file then you can replace the header with below code.

Export data in CSV file

$headers = [
'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
'Content-type' => 'text/csv',
'Content-Disposition' => 'attachment; filename=file_name.csv',
'Expires' => '0',
'Pragma' => 'public'
];

If you get error like “Class Response not found” then add below line after the namespace,

use Response;

This is how we can generate Excel or CSV file from array without any package.

--

--