Our blog

 

PHP : Dead Easy Excel Export

Some people like their excel files. For people who want their data exported in an excel format checkout this chunk of code. It's really easy :-)

First of all you need to download this php excel class

Now try this code:

PHP:
  1. $query = mysql_query("select * from table");
  2. while($q = mysql_fetch_assoc($query)){
  3.     $output[] = $q;
  4. }
  5. require_once "excel.php";
  6. $export_file = "xlsfile://export.xls";
  7. $fp = fopen($export_file, "wb");
  8. if (!is_resource($fp))
  9. {
  10.     die("Cannot open $export_file");
  11. }
  12. fwrite($fp, serialize($output));
  13. fclose($fp);
  14. header ("Content-Type: application/x-msexcel");
  15. header ("Content-Disposition: attachment; filename=\"exports.xls\"" );
  16. readfile("xlsfile://export.xls");

That's got to be the easiest thing you have ever done in PHP. Thanks goes to the excellent PHP Classes site.

Here is some further reading:
PHP Excel Formula Parser
PHP Excel Export class
Export data directly to Excel by configuring the MIME Type Profile Option
Power your PHP Business Logic with Excel
Reading/Parsing Excel Spreadsheet using PHP

More Reading:

2 Comments

admin
July 14th, 2008

Note - on a unix/linux host this code might not work

to fix this try the following.

line 71 of the excel class

PHP:
  1. function stream_open($path, $mode, $options, &$opened_path)
  2.     {
  3.         /* lets do it quick and dirty
  4.         $url = parse_url($path);
  5.         $this->xlsfilename = '/' . $url['host'] . $url['path'];
  6.         $this->xlsfilename = $url['host'] . $url['path'];
  7.         */
  8.         $this->xlsfilename = str_replace('xlsfile://', '', $path);

 

Dave Gee
May 10th, 2010

Is my website outdated for today's programmers demands?

 

 

Leave a Reply