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", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0);
return;
}
<?php
// Function to generate Excel File header
function xlsBOF() {
echo pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0);
return;
}
// Function to generate Excel File Footer
function xlsEOF() {
echo pack("ss", 0x0A, 0x00);
return;
}
function xlsEOF() {
echo pack("ss", 0x0A, 0x00);
return;
}
// Function to write a Number (double) into a
Cell in Excel
function xlsWriteNumber($Row, $Col, $Value) {
echo pack("sssss", 0x203, 14, $Row, $Col, 0x0);
echo pack("d", $Value);
return;
}
function xlsWriteNumber($Row, $Col, $Value) {
echo pack("sssss", 0x203, 14, $Row, $Col, 0x0);
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, 8 + $L, $Row, $Col, 0x0, $L);
echo $Value;
return;
}
?>
The following is the code to generate excel file.
function xlsWriteLabel($Row, $Col, $Value ) {
$L = strlen($Value);
echo pack("ssssss", 0x204, 8 + $L, $Row, $Col, 0x0, $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
?>
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
?>
It works great. Simple yet easy to understand :)
ReplyDelete