Sunday, August 9, 2009

Create excel (.xls) file with PHP.

"Excel files are very useful for managing data and calculations.
People want to save their catalog data and calculations to an excel file. They always in the need of an automated solution for their web-stores and office work."

We will use a php class to accomplish this task. You can find this class at
phpclasses.org or (Click Here)

I am going to generate a simple excel sheet which will contain 2 columns (Name and Age).

(Hopefully):

Name Age
Mattias 25

Tony 30

Peter 35

Edvard 54
require_once “excel.php”; //php class downloaded from phpclasses.org
$filename = “theFile.xls”;
// File name to save at server.

The next code will open the file at the server. If it is not present it will create it at the server automatically.

$export_file = “xlsfile://tmp/”.$filename;
$fp = fopen($export_file, “wb”);
if (!is_resource($fp))
{
die(”Cannot open $export_file”);
} // typically this will be generated/read from a database table

Now we will create array to put data into the excel sheet.

$assoc = array(
array(”Name” => “Mattias”, “Age” => 25,
array(”Name” => “Tony”, “Age” => 30,
array(”Name” => “Peter”, “Age” => 35,
array(”Name” => “Edvard”, “Age” => 54);

fwrite($fp, serialize($assoc));
fclose($fp);

If you want to open the file in the browser. Add the following code at the end of the page.

header (”Expires: Mon, 26 Jul 1997 05:00:00 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=\”" . $filename . “\”" );
header (”Content-Description: PHP/INTERBASE Generated Data” );
readfile($export_file);
exit;

It is a complete solution that can be use to write excel files with PHP. Kindly write your comments about this code.

No comments:

Post a Comment

All rights are reserved. Nobleatom.com
Software Development Services.
Contact me: khubabmazhar596@hotmail.com

Web Design Increase Page Rank Internet blogs DigNow.net web directory1Abc DirectorySeo friendly web directory