Creating excel files through PHP

Want to help support this blog? Try out Oh Dear, the best all-in-one monitoring tool for your entire website, co-founded by me (the guy that wrote this blogpost). Start with a 10-day trial, no strings attached.

We offer uptime monitoring, SSL checks, broken links checking, performance & cronjob monitoring, branded status pages & so much more. Try us out today!

Profile image of Mattias Geniar

Mattias Geniar, June 04, 2008

Follow me on Twitter as @mattiasgeniar

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.



Want to subscribe to the cron.weekly newsletter?

I write a weekly-ish newsletter on Linux, open source & webdevelopment called cron.weekly.

It features the latest news, guides & tutorials and new open source projects. You can sign up via email below.

No spam. Just some good, practical Linux & open source content.