Creating excel files through PHP

No need to use complicated or extensive libraries (such as PEAR) to create Excel pages. Just take advantage of the "smart" part of Excel; its ability to parse an HTML table to a nice Excel page.

Just create a regular .PHP file, where you output your data in a nice little html-table. Then place the following snippet in the top of that file (no output can happen before these lines, as they change your headers -- so place these all the way at the top):

header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=excel.xls");

And it's just that easy. If you open the page, you'll see a download-window asking you where to place the file. The headers will tell your computer that it's an Excel-file, which will parse your html-table (assuming you've written it without errors) and display it nicely.

If that's not enough, you can look at more extensive libraries such as PHPExcel. As their examples show, it offers more advanced features.

Looking for help?

Tired of fixing all these tech-problems yourself? We've got an excellent team at Nucleus, a top-class Belgian hosting provider, that can help you. Discover our Managed Hosting, where skilled engineers manage your servers and keep them up-to-date, so you can focus on your core business. We use a variety of Configuration Management Systems such as Puppet to make sure every config is reviewed, unit-tested and guaranteed to be working.

Want to get in touch? Find me as @mattiasgeniar on Twitter or via the contact-page on my blog.

Tagged with: , ,
Posted in php
65 comments on “Creating excel files through PHP
  1. André says:

    Hi,
    great!
    But i have a Problem with UTF8 cyrillic :(
    just strange Signs :(

    added
    header(“Content-Type: text/html; charset=utf-8″);
    header(“Content-type: application/vnd.ms-excel”);
    header(“Content-Disposition: attachment; filename=excel.xls”);

    excel.php is saved as UTF8

    still not working :(

    any solutions??

    THX

  2. nick says:

    Using this or other code like it I can make the file pop up on the browser to open or save. But how can I attach the file to an email and send it instead of opening it or saving it?

  3. paris says:

    Thank you . I left hope before coming to your site. Gave a last try and it worked thanks a lot

  4. Egbert O'Foo says:

    You’ll need some way to communicate to your downloader that he/she should expect to see a warning when Excel (2010) detects it has to do a conversion.

    But, it works Just Fine(tm) otherwise. Thank you!

  5. John says:

    If I style my html table will the colors and stuff go along with it?

Leave a Reply

Your email address will not be published. Required fields are marked *

*

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>