How to Generate MS-Excel file using PHP

5 comments
After writing PDF file with PHP, I think it will be nice to write an excel file with PHP. The script is very simple. There are different functions to write numbers and text. Start and end of file is also defined by separate functions. Just have a look on how it works.

Live Demo Download Script


PHP Code

<?
// Connect database. 
include "../connect.php";

// Functions for export to excel.
function xlsBOF() { 
echo pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0); 
return; 
} 
function xlsEOF() { 
echo pack("ss", 0x0A, 0x00); 
return; 
} 
function xlsWriteNumber($Row, $Col, $Value) { 
echo pack("sssss", 0x203, 14, $Row, $Col, 0x0); 
echo pack("d", $Value); 
return; 
} 
function xlsWriteLabel($Row, $Col, $Value ) { 
$L = strlen($Value); 
echo pack("ssssss", 0x204, 8 + $L, $Row, $Col, 0x0, $L); 
echo $Value; 
return; 
} 
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");;
header("Content-Disposition: attachment;filename=result.xls "); 
header("Content-Transfer-Encoding: binary ");

xlsBOF();

/*
Make a top line on your excel sheet at line 1 (starting at 0).
The first number is the row number and the second number is the column, both are start at '0'
*/
xlsWriteLabel(0,0,"Cool PHP to Excel Tutorial by WebsSpeaks.in");

xlsWriteLabel(2,0,"Name-");xlsWriteLabel(2,1,"Arvind Bhardwaj");
xlsWriteLabel(2,2,"Phone-");xlsWriteLabel(2,3,"9999492584");
xlsWriteLabel(3,0,"Email-");xlsWriteLabel(3,1,"bhardwajsonheight@gmail.com");

// Make column labels. (at line 3)
xlsWriteLabel(6,1,"Sr. No.");
xlsWriteLabel(6,3,"Tutorial.");

$xlsRow = 7;

// Put data records from mysql by while loop.
 $result=mysql_query("select * from records order by msg_id");
 while($row=mysql_fetch_array($result))
 {
  xlsWriteNumber($xlsRow,1,"{$row['msg_id']}");
  xlsWriteLabel($xlsRow,3,"{$row['message']}");
  $xlsRow++;
 }
xlsEOF();
exit();
?>

5 comments

I аm in fаct gratеful to the owneг
of this ωeb page who has sharеԁ this fantastic post аt here.


My weblog ... site
Also visit my web blog ::

but when i open execel sheet file error will be generate "data may have been lost"

We would love to hear from you...

back to top