PHPExcel – View Discussion, exporting the result of a MySQL query to Excel

// connection with the database 
$dbhost = "localhost"; 
$dbuser = "root"; 
$dbpass = ""; 
$dbname = "database"; 


// require the PHPExcel file 
require 'Classes/PHPExcel.php'; 

// simple query 

$query = "SELECT username,emailAdress,locationCity FROM users ORDER by id DESC"; 
$headings = array('User Name', 'EMail Address','City'); 

if ($result = mysql_query($query) or die(mysql_error())) { 
    // Create a new PHPExcel object 
    $objPHPExcel = new PHPExcel(); 
    $objPHPExcel->getActiveSheet()->setTitle('List of Users'); 

    $rowNumber = 1; 
    $col = 'A'; 
    foreach($headings as $heading) { 

    // Loop through the result set 
    $rowNumber = 2; 
    while ($row = mysql_fetch_row($result)) { 
       $col = 'A'; 
       foreach($row as $cell) { 

    // Freeze pane so that the heading line won't scroll 

    // Save as an Excel BIFF (xls) file 
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); 

   header('Content-Type: application/'); 
   header('Content-Disposition: attachment;filename="userList.xls"'); 
   header('Cache-Control: max-age=0'); 

echo 'a problem has occurred... no data retrieved from the database';

PHPExcel – View Discussion.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s