Data Export In Excel

In this tutorial we will discuss about export data to Excel in PHP. We will create this project because many places in our project we are needed to provide export to Excel functionality. So the user can easily access and view their data through an excel file. With the script shows below you can easily implement the export data to Excel functionality using PHP.

Sample Code

For The Function of exporting the data in a .ms-excel format.
  1. <php>function filterData(&$str)
  2. {
  3. $str = preg_replace("/\t/", "\\t", $str);
  4. $str = preg_replace("/\r?\n/", "\\n", $str);
  5. if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
  6. }
  7. $fileName = "excelexport" . date('Ymd') . ".xls";
  8. header("Content-Disposition: attachment; filename=\"$fileName\"");
  9. header("Content-Type: application/.ms-excel");
  10.  
  11. $flag = false;
  12. foreach($data as $row) {
  13. if(!$flag) {
  14. echo implode("\t", array_keys($row)) . "\n";
  15. $flag = true;
  16. }
  17. array_walk($row, 'filterData');
  18. echo implode("\t", array_values($row)) . "\n";
  19. }
  20. ?>
And for the Data Array Script for exporting the data through Excel file.
  1. <?php
  2. $data = array(
  3. array("First Name" => "Reynan", "Last Name" => "Serion", "Email" => "[email protected]", "Message" => "Message For Reynan"),
  4. array("First Name" => "Rolyn Jasper", "Last Name" => "Demirin", "Email" => "[email protected]", "Message" => "Message For Rolyn Jasper"),
  5. array("First Name" => "Jasper", "Last Name" => "Claro", "Email" => "[email protected]", "Message" => "Message For Jasper"),
  6. array("First Name" => "Rocky", "Last Name" => "Basa", "Email" => "[email protected]", "Message" => "Message For Rocky")
  7. array("First Name" => "Van-Van", "Last Name" => "Nav", "Email" => "[email protected]", "Message" => "Message For Van-Van")
  8. );
  9. ?>
resultHope that you learn in this tutorial and enjoy coding. Don't forget to LIKE & SHARE this website. If you do have any problems or suggestions in your projects or programming, then just visit this website http://www.sourcecodester.com/ for more updates and programming ideas.

Add new comment