Wednesday, August 3, 2011

How to export mysql data to excel file


I've been able to export any data from MySQL to a csv file.

Export mysql data to excel in php 

Code here :

<?php
$topRow="<table border='1'>";
$bottomRow="</table>";
$columns="<tr><th>Name</th><th>Age</th><th>Phone/Mobile Number</th>";
$columns.="</tr>";
$data="";
$i==1;
///////////////////////////
/// you can also connect database. you fetch data and pass paramete on td tag fields.
/////////////////////
while($i<10){
$nName="<tr><td>".str_replace('"', '""',"Jafar Khan")."</td>";
$age="<td>".str_replace('"', '""',"24")."</td>";
$phoneMobileNumber="<td>".str_replace('"', '""',"9451293997")."</td>";
$line=$nName.$age.$phoneMobileNumber;
 $data.=$line;
$i++ ;}
$data = str_replace("\r", "", ($topRow.$columns.$data.$bottomRow));
function exportToExcelUtil($filename,$data) {
        header("Content-type: application/octet-stream");
        header("Content-Disposition: attachment; filename=$filename");
        header("Pragma: no-cache");
        header("Expires: 0");
        echo  $data;
    }
exportToExcelUtil("test.xls",$data);
?>

No comments:

Post a Comment