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.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Mohit Mehta
Mohit Mehta

Written by Mohit Mehta

Full stack enthusiastic developer

No responses yet

Write a response