Learn About Doug!
View Doug Boude's online resume
updated 4/22/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)
Contact Doug!
OO Lexicon
Chat with Doug!
Recent Entries
You may also be interested in...
Florida web site design



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)
<< July, 2009 >>
SMTWTFS
1234
567891011
12131415161718
19202122232425
262728293031
Search Blog

Recent Comments
Re: Equivalent of SQL "TOP X" in Oracle (by Azzedo at 7/01 4:39 PM)
Re: Small But Seriously Irritating Export to Excel Issue (by dougboude at 6/30 2:47 PM)
Re: Small But Seriously Irritating Export to Excel Issue (by Shannon Hicks at 6/30 1:41 PM)
Re: Disappearing IE Popup Window During Save/Open Dialog (by James Moberg at 6/26 7:17 PM)
Re: Buying a New Home in San Antonio (by ike at 6/26 2:58 PM)
Re: SQL Forward Engineering with Visio 2003 Professional (by Matthew at 6/17 2:33 PM)
Re: Special Character/Unicode Issue in Ajax Data Retrieval (by matt at 6/15 3:34 AM)
Re: My Twelve Steps to a Coldbox App (by Dutch Rapley at 6/12 1:34 PM)
Re: My Twelve Steps to a Coldbox App (by dougboude at 6/12 12:09 PM)
Re: My Twelve Steps to a Coldbox App (by Dutch Rapley at 6/12 11:52 AM)
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 | 0 comments



Small But Seriously Irritating Export to Excel Issue

Alright boys and girls, here is an issue and its solution that had me going NUTS for a couple of hours. I actually wrote and implemented three DIFFERENT solutions trying to find a way around the problem, only to find out in the end that I kept carrying the true issue with me.

The Scenario

My user clicks a link and a window pops up allowing them to save or open some exported data as an Excel spreadsheet. Of course, it all worked fine on my machine (two of them, actually), but when my boss tried it on his, he got an error. Not cool. Back to the drawing board.

The Challenge

My first attempt (which worked fine for me) was to create a true excel spreadsheet by streaming the data in binary to a file (it's a bit complicated, but cool). Excel 2007 was able to open it just fine, but my boss' older 2003 could not. So, I decided I'd just fall back on the old reliable CSV type file rather than try and troubleshoot the first approach in too much depth. I coded my CSV export and for the life of me could NOT get my Excel to open it without first flashing me with two nasty error messages, paraphrased here:

"The file you are trying to open '[file name here]' is in a different format than specified by the file extension."

"Excel has detected that '[filename here]' is a SYLK file, but cannot load it."

What the heck??? All we're talking about is some text separated by a comma. And Excel doesn't recognize the format??? Content headers are right; file extension is right; Open it up in a text editor and it sure looks fine to me; What's going on?

I reworked the code to use tabs as delimiters; same symptoms.

The Solution

After dicking with it for a couple of hours, comparing known working CSVs with the one I generated, comparing non printable character strings such as line feeds (which is what I suspected the issue to possibly be), I finally figured out that the TRUE problem was (and I grit my teeth in frustration when saying this): the name of the first column in my data.

NEVER allow the first column in your data to be called "ID". AUGH!!!! (had to scream). Apparently, using "ID" is a trigger to Excel that your file contains a symbolic link to another spreadsheet somewhere. I know, I know, for every OTHER type of file that Excel opens it relies on the file's EXTENSION to determine the type; but not in this case.

Moral of the story: NEVER allow the first column in your CSV data to be called "ID".

Lesson learned, I'm now one small step closer to Nirvana.

Posted by dougboude at 12:30 PM | PRINT THIS POST! | Link | 2 comments