Tuesday, December 17, 2013

Generating Excel files using PHP

In this tutorial we will be learning how to generate a basic excel file using PHP without using any third party libraries. For generating excel sheets with styling, we need to use other libraries.

The following are the functions, which you can write in your main PHP file or in an external file and include it in your main file.

<?php 
// Function to generate Excel File header 
function xlsBOF() { 
    echo 
pack("ssssss"0x8090x80x00x100x00x0);  
    return; 
} 

// Function to generate Excel File Footer 
function xlsEOF() { 
    echo 
pack("ss"0x0A0x00); 
    return; 
} 

// Function to write a Number (double) into a Cell in Excel
function xlsWriteNumber($Row$Col$Value) { 
    echo 
pack("sssss"0x20314$Row$Col0x0); 
    echo 
pack("d"$Value); 
    return; 
} 

// Function to write a label (text) into Cell in Excel 
function xlsWriteLabel($Row$Col$Value ) { 
    
$L strlen($Value); 
    echo 
pack("ssssss"0x204$L$Row$Col0x0$L); 
    echo 
$Value; 
return; 
} 
?> 

The following is the code to generate excel file.

<?php 
// Headers to inform browser that the file is excel
header 
("Expires: "gmdate("D,d M YH:i:s") . " GMT"); 
header ("Last-Modified: " gmdate("D,d M YH:i:s") . " GMT"); 
header ("Cache-Control: no-cache, must-revalidate");     
header ("Pragma: no-cache");     
header ('Content-type: application/x-msexcel'); 
header ("Content-Disposition: attachment; filename=Sample.xls" );  
header ("Content-Description: PHP/INTERBASE Generated Data" ); 
// 
// the following is the code to add content to the Excel stream 
// 
xlsBOF();   // begin Excel file 
xlsWriteLabel(0,0,"This is a label");  // write a text in A1 cell  (row 1, column 1) 
xlsWriteNumber(0,1,9999);  // write a number in B1 cell (row 1, column 2) 
xlsEOF(); // end of Excel file 
?>

This is the simplest and easiest way to generate Excel file in PHP. As mentioned at the beginning of this tutorial, to generate more complex Excel files with styling and other formatting, you need to use other libraries.

1 comment :