Tuesday, August 9, 2016

Export Excel files in CSV format with UTF-8 encoding in Laravel

Case : You are given  2 dates ($dateFrom , $dateTo) and you have to find data within given range and export this data in csv format which can encode utf-8 character set.

We can divide this whole process in 2 parts.

First( Get Data)

$first_date = date('Y-m-d 00:00:00', strtotime($dateFrom));
$last_date  = date('Y-m-d 23:59:59', strtotime($dateTo));
Now get data from database: 
$admission_details_all=$this->getCompletedReportResult($first_date,$last_date);
Second(Export To Csv)
 First we have to define , which field we want to show in csv file.

So declare fields in an array as follow :

$arrColumns = array('name', 'phone_no', 'branch_name', 'course_name');

and remember this fields represents the field name you'll query from database.

The define first row of the csv file:

$arrFirstRow = array('Name', 'Phone No', 'Branch', 'Course');
$options = array(    'columns' => $arrColumns,    'firstRow' => $arrFirstRow,);
now create a function convertToCSV($admission_details_all, $options, $dateFrom ,$reportType) 
$admission_details_all is the data we get from database
$options is an array which has $arrColumns and $arrFirstRow
$dateFrom is a date time required to track when you exported your file
$reportType is required to name the exported file
now we have to call  convertToCSV function and return it.
return $csvconversionrepo->convertToCSV($admission_details_all, $options, $dateFrom ,$reportType); 
Here is the screen shot of  convertToCSV funtion
 

Related Posts:

  • Api authorization with Passport in Laravel 5.3 This tutorial is basically an environment set up to understand how Passport works in Laravel 5.3. Passport is a way to manage authentication for accessing API in Laravel. It is very easy to implement and user do not need to… Read More
  • Integrate Redis on Laravel 5.2 In this tutorial i am going to write basic steps to integrate Redis with laravel 5.2  Steps First Install Redis server on your system. I am using  Ubuntu 14.04. Following commands will setup Redis Server on … Read More
  • Laravel 5.3 default authentication In this tutorial i'll give  basic idea of authentication system provided by laravel 5.3. You can find more details about authentication system in this video tutorial. Authentication system is one of the core module o… Read More
  • Up & Running With Gulp Check Older version if installed $ npm rm --global gulp   Install Gulp Globally $ npm install --global gulp-cli Initializing Project directory npm init Installing Dependencies npm install --save-dev gulp Creatng gu… Read More
  • Install laravel 5.3 in Ubuntu 14.04 Once again Laravel comes with many amazing features and i can't wait more to try this all out. In this post i am going to write how to setup laravel 5.3 in Ubuntu 14.04. I am planning on making video for each of this … Read More

0 comments:

Post a Comment