Sign Doug's SOTR Petition!

Sign Doug's petition to his boss and help send him to Scotch on the Rocks in 2012!
Recent Entries
Contact Doug!
Learn About Doug!
View Doug Boude's online resume
updated 11/18/2009

View Doug Boude's profile on LinkedIn
Link to me!

Follow Doug Boude on Twitter
Follow me!

Be Doug's friend on Facebook
Befriend me!
(I promise not to follow you home)
OO Lexicon
Chat with Doug!
NO MORE CAREER
POLITICIANS!
Get Out Of Our House: Replacing congress with TRUE citizens!
You may also be interested in...
Web Hosting
best web hosting - top web hosting sites, thetop10bestwebhosting.com

Czech your Page Rank!
Check Page Rank of any web site pages instantly:
This free page rank checking tool is powered by Page Rank Checker service
Surf's Up!
Visit Egosurf.org and massage YOUR web ego!
My Score: 9,001
Doug's Books

Read (and recommend)

  • Men are from Mars, Women are from Venus
  • The Wisdom of Crowds: Why the Many Are Smarter Than the Few and How Collective Wisdom Shapes Business, Economies, Societies and Nations
  • Blink: The Power of Thinking Without Thinking
  • Head First Design Patterns
  • Transact-SQL Programming
  • What's So Amazing About Grace?
  • Just So Stories (Rudyard Kipling collection)

Reading

  • Prayer: Does it Make Any Difference?
  • Data Mining (Practical Machine Learning Tools and Techniques)
<< February, 2012 >>
SMTWTFS
1234
567891011
12131415161718
19202122232425
26272829
Search Blog

Recent Comments
Re: Basic Ajax Select List Filter in PHP (by opineemia at 2/02 8:47 PM)
Re: PHP vs COLDFUSION (by dougboude at 1/24 9:47 AM)
Re: PHP vs COLDFUSION (by WhatTheHeck at 1/23 7:03 PM)
Re: Recursive Functions in ColdFusion (by Marty McGee at 1/22 1:01 PM)
Re: SQL Forward Engineering with Visio 2003 Professional (by Rama at 1/10 11:05 AM)
Re: PHP Export to Excel Snippet (by rasha at 1/10 1:55 AM)
Re: Fredrick "French" Fry (by Picky eater at 1/09 2:21 PM)
Re: Disappearing IE Popup Window During Save/Open Dialog (by Vivekanand at 1/06 12:51 AM)
Re: Just What IS a 'Service Layer', Anyway? (by Ashishkumar Haldar at 1/05 7:49 AM)
Re: Viewing Option Text (in IE7) that's Wider than the Select List (by ranjit sachin at 12/20 6:22 AM)
Re: Recursive Functions in ColdFusion (by Jason at 12/15 12:13 PM)
Re: Viewing Option Text (in IE7) that's Wider than the Select List (by kt at 12/08 3:47 AM)
Re: PayPal IPN Coldfusion CFC (by Guest at 11/28 6:11 PM)
Re: SQL Forward Engineering with Visio 2003 Professional (by freddy villamil at 11/09 2:49 PM)
Re: Finally Found a Use for CFTHREAD (by criclebrava at 11/09 1:23 PM)
Re: Finally Found a Use for CFTHREAD (by assisisowsfub at 11/07 10:37 PM)
Re: IRRITATING CF QUERY ERROR AND SOLUTION (by dougboude at 10/10 10:48 AM)
Re: Using Google as your CF Mail Server (by hlharkins at 10/09 10:24 AM)
Re: IRRITATING CF QUERY ERROR AND SOLUTION (by Peter Boughton at 10/07 3:15 PM)
Re: My Thoughts on the Current Presidential Contenders (by dougboude at 9/23 12:21 PM)
Categories
Archives
Photo Albums
Funnies (5)
Family (3)
RSS

Powered by
BlogCFM v1.11

30 June 2009
PHP Export to Excel Snippet

For those PHPers out there who are doing an export to Excel, I thought I'd share the solution I came up with. I realize there are already a gabillion examples out there, but I merged some of the better approaches from a few of them that made it fairly elegant, I think (such as leveraging the implode, array_keys, and array_values functions).

Without further adieux...

<?php
//your code here to create your sql statement...we'll call it $finalSQL
 
//go get the data we need...
$Result=mysql_db_query($DBName,$finalSQL,$Link);
//fetching each row as an array and placing it into a holder array ($aData)
while($row = mysql_fetch_assoc($Result)){
 $aData[] = $row;
}
//feed the final array to our formatting function...
$contents = getExcelData($aData);

$filename = "myExcelFile.xls";

//prepare to give the user a Save/Open dialog...
header ("Content-type: application/octet-stream");
header ("Content-Disposition: attachment; filename=".$filename);

//setting the cache expiration to 30 seconds ahead of current time. an IE 8 issue when opening the data directly in the browser without first saving it to a file
$expiredate = time() + 30;
$expireheader = "Expires: ".gmdate("D, d M Y G:i:s",$expiredate)." GMT";
header ($expireheader);

//output the contents
echo $contents;
exit;
?>

<?php
 function getExcelData($data){
    $retval = "";
    if (is_array($data)  && !empty($data))
    {
     $row = 0;
     foreach(array_values($data) as $_data){
      if (is_array($_data) && !empty($_data))
      {
          if ($row == 0)
          {
              // write the column headers
              $retval = implode("\t",array_keys($_data));
              $retval .= "\n";
          }
           //create a line of values for this row...
              $retval .= implode("\t",array_values($_data));
              $retval .= "\n";
              //increment the row so we don't create headers all over again
              $row++;
       }
     }
    }
  return $retval;
 }
?>

 

 




Posted by dougboude at 1:06 PM | PRINT THIS POST! |Link | 10 comments
Subscription Options

You are not logged in, so your subscription status for this entry is unknown. You can login or register here.

Re: PHP Export to Excel Snippet
Great script! Thanks for posting. I am curious why the exports all begin on row 11 in Excel for me as opposed to row 1. Any ideas? Thanks again...this is great.

Tom
Posted by tomw on November 25, 2009 at 1:45 PM

Re: PHP Export to Excel Snippet
this script generated double column for each entry so if table contain 3 column then excel file will ocntain 6 olumn
sorry for bad typing
Posted by susheel on February 1, 2010 at 5:54 AM

Re: PHP Export to Excel Snippet
reply me at my email : sushe3l@gmAIL.COM
Posted by susheel on February 1, 2010 at 6:06 AM

Re: PHP Export to Excel Snippet
that's the best code i have come across so far that walks the talk.Thanks!
Posted by james on April 17, 2010 at 4:28 AM

Re: PHP Export to Excel Snippet
"foreach(array_values($data) as $_data)" is too complicated. "foreach($data as $_data)" will suffice.
Posted by bob on May 25, 2010 at 2:12 PM

Re: PHP Export to Excel Snippet
It is a wonderful snippet.
However, on Excel 2007, it generated a warning message: "The file you are trying to open, is in a different format than specified by the extension. Verify that the file is not corrupted and is from a trusted source before opening the file. Do you want to open the file now?

I did open the file and needed to save it in version 2007 xlsx format.

Ben
Posted by Ben Lam on May 6, 2011 at 1:15 PM

Re: PHP Export to Excel Snippet
I'm getting the following error. Any suggestions?

Access denied for user 'loanmod1'@'localhost' (using password: NO)
Posted by Denise Cowen on July 4, 2011 at 3:09 PM

Re: PHP Export to Excel Snippet
@Denise,

My best guess based on what you shared is that your query is failing due to a permissions issue. I would look at the database link you're creating and make sure the credentials are correct. Make sense?

Doug
Posted by dougboude on July 5, 2011 at 9:29 AM

Re: PHP Export to Excel Snippet
that's Gr8 i am really thankful to u
and if possible then plz inform me about export to pdf
Posted by Ashish Sharma on September 10, 2011 at 4:13 AM

Re: PHP Export to Excel Snippet
what about styling the sheet? any ideas?
Posted by rasha on January 10, 2012 at 1:55 AM

Name:   Required
Email:   Required your email address will not be publicly displayed.

Want to receive notifications when new comments are added? Login/Register for an account.

Time to take the Turing Test!!!

Three plus Twenty equals
Type in the answer to the question you see above:

Your comment:

Sorry, no HTML allowed!