Web Development Blog

by Ei Sabai Nyo

19 Sep, 2007

Export into excel with formula in PHP    

In PHP, exporting data into an excel file (.csv) can be achieved very easily by sending a raw HTTP header. And having a formula in cells is no brainier either (and I only found that out after searching through google and not finding any solution – hehe).

The following is a rough example of how you do it. What I am trying to do here as an example is have an excel formula in Age column to calculate the person’s age automatically.

        header('Content-Type: application/csv');
        header('Content-Disposition: inline; filename="report.csv"');  

        // print column titles
        echo 'Name,Year born,Age' . "\n";  

        // a full numeric representation of a year, 4 digits; eg: 2007
        $year = date('Y'); 

        // $count starts from 2 because the first row is reserved for column titles
        $count = 2;  

	while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { 
 	    echo $row['name'] . ',';
            echo $row['year'] . ',';
            // formula = Current year - Bx(Year born)  B is the column position
            echo '=' . $year . '-B' . $count; 
            echo "\\n"; 
            // increment $count by 1 (same as $count = $count + 1)
            $count++; 
        }
        exit;

Technorati Tags: , , ,

Love what you've just read? Subscribe to our newsletter to receive tips, resources and special offers related to web development & design.
Your name:   Your email:  

Comments are closed.

Profile PicHello! Welcome to Web development blog! My name is Ei Sabai and on this blog, I write about web development, mobile app development, latest web technologies and the likes. Read more about me or have a look at some of the tips & resources I've written.
Subscribe to our newsletter to receive tips, resources and special offers related to web development & design.
We do NOT spam.
Your name:  
Your email:  

Tips & Resources

Tips & Resources
WordPress Web Hosting
Recommended web hosting providers for WordPress 3.0
iPhone Native App Development
Important steps into iPhone app development for beginners
iPhone Web App Development
Tips for iPhone web app development
Coupons for Web Developers
Get discounts on web hosting, domain names, templates, etc
10 Useful jQuery Snippets
Easy-to-use jQuery snippets for any website
HTML Email Newsletter
Step-by-step tutorial on how to code an HTML email newsletter
  • bluehost Hosting $6.95/month
  • Joomla Templates

Recommended Book

Categories