View Single Post
Old 27-Feb-2007, 08:59 PM   #2 (permalink)
Sangeetha
Fixed Error!
 
Sangeetha's Avatar

Posts: 139
Location: Chennai
Join Date: Feb 2007
Rep Power: 2 Sangeetha is on a distinguished road

IM:
Default Re: export as xls table

Welp, I guess since everyone is posting code.... this is a bit of code from a project I did. It emits a csv file, which isn't real excel, but excel will open it automatically:

if ($mode=='csv')
{
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="file.csv"');
echo csv($tab);
exit;
}

/**
* Emit a csv version of the tab.
*/
function csv($tab)
{
global $tabpath;
$dq = '"';
$file = file_get_contents( "$tabpath/$tab" );
$file = normalize( $file );
list( $totalHours, $rate, $total, $litFile, $error ) = calculate( $file );
$lines = preg_split( '/\n/s', $file );
foreach( $lines as $line )
{
$parts = preg_split('/ - /', $line);
$o .= $dq.$parts[0].$dq.',';
$o .= $dq.$parts[1].$dq.',';
$o .= $dq.$parts[2].$dq.',';
$o .= $dq.csvquote($parts[3]).$dq.',';
$o .= $dq.preg_replace('/ minutes/','',$parts[4]).$dq.',';
$o .= "\r\n";
}
return $o;
}

function csvquote( $s )
{
$s = preg_replace('/"/','""', $s);
return $s;
}


I would modify the csv function like this. It takes a mysql result as an argument:

/**
* Emit a csv version of the result.
*/
function csv($result)
{
$dq = '"';
while( $row = mysql_fetch_row($result) )
{
while( list($key,$value) = each($row) )
{
$o .= $dq.csvquote($value).$dq;
}
$o .= "\r\n";
}
return $o;
}
Sangeetha is offline   Reply With Quote