Tuesday, July 28, 2009

Export data to Excel in PHP

I will show you how to export data html to excel using php with oop implementation.
1. Create file viewhtml.php and excel.class.php(class file)

2. Write code in viewhtml.php :
*******************************

<?

ob_start(); //output buffering is active no output is sent from the script

include 'excel.class.php';

$data = "<table><tr><td>The Greatest Post</td><td>dot blogspot</td></tr></table>"; // the data you want to print

echo $data;

if(isset($_GET['export'])){

for ($i=1;$i<=5;$i++){
echo $data;
}

$create = new Excel; // create obj.

$create->CreateExcel($data,$_GET[export]); //call func. creat

}

?>

<a href="viewhtml.php?export=sini_letak_nama_file">Export Excel</a>

3. Write code in excel.class.php

**************************************

<?php

class Excel {

function CreateExcel($datatoprint,$filename){
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=$filename.xls");
header("Pragma: no-cache");
header("Expires: 0");
echo $datatoprint;
}

}

?>

**********************************************

4. Run page viewhtml.php then click link to test.
Have try....!!


No comments: