Edmonds Commerce Logo
  • home
    • blog
  • ecommerce
    • product catalogue
    • order processing
    • customer services
    • stock control
    • human resources
    • management information
  • development
    • oscommerce
    • php
    • mysql
    • open source
    • performance tuning
  • design
  • marketing
  • contact us
    • pricing

Edmonds Commerce Blog

Freelance PHP Ecommerce and SEO Developer in the UK

Latest Posts

Zend_Dojo Dijits and Numeric ID’s
Happy New Year from Edmonds Commerce
Easy Security for PHP Scripts
Secure and Insecure Contents in HTTPS

Most Popular Posts

PHP Email Attachment Function Freelance osCommerce UK Ultimate osCommerce Checkout - Fast and Friendly PHP : Dead Easy Excel Export

PHP : Dead Easy Excel Export

July 9th, 2008
Read More excel, php

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:

PLAIN TEXT
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");
  17. exit;

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

Feed | Respond | Trackback

One Response to “PHP : Dead Easy Excel Export”

  1. admin Says:
    July 14th, 2008 at 9:42 am

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

    to fix this try the following.

    line 71 of the excel class

    PLAIN TEXT
    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);

Leave a Reply

To use reCAPTCHA you must get an API key from http://recaptcha.net/api/getkey