Pages

Sunday 3 March 2013

How to convert PHP table to excel file

Hello everyone!!
                    Today I am posting an easy code to convert PHP table into an excel file. Here it is:

<?php


$SQL="SELECT * FROM tbl_name";
$result=mysql_query($SQL) or die("Error, query failed");

$num=mysql_numrows($result);

$export = mysql_query ( $SQL ) or die ( "Sql error : " . mysql_error( ) );

$fields = mysql_num_fields ( $export );

for ( $i = 0; $i < $fields; $i++ )
{
$header .=mysql_field_name( $export , $i ) ."\t";
}
while( $row = mysql_fetch_row( $export ) )
{
$line = '';
foreach( $row as $value )
{
if ( ( !isset( $value ) ) || ( $value == "" ) )
{
$value = "\t";
}
else
{
$value = str_replace( '"' , '""' , $value );
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}

$data .= trim( $line ) . "\n";
}

$data = str_replace( "\r" , "" , $data );

if ( $data == "" )

{

$data = "\n(0) Records Found!\n";

}
header("Content-type: application/octet-stream");

header("Content-Disposition: attachment; filename="filename.xls");

header("Pragma: no-cache");

header("Expires: 0");

print "$header\n$data";


?>

                                       Hope it was helpful to all. Keep tuned for more stuff.
                                                                                                                         - N K Sran


No comments:

Post a Comment