Solved

How to export my MySQL query results into a formated Excell spreadsheet?

Posted on 2009-07-07
14
341 Views
Last Modified: 2013-12-13
Experts,

I have a complex query that prints query results to a page.  I would like to allow my users to download the query results in a formatted Excell Spreadsheet.  Is this possible?

My query is below.  EVM
<?php

				 if($_GET['cmd']=="getsums"){

				 mysql_connect("localhost", "user", "password")or die("cannot connect");

				 mysql_select_db("dsadb2")or die("cannot select DB");

		  

		 		 $sql2="SELECT @rownum:=@rownum + 1 'rank', a.NUID,sum(a.Steps) as total_steps, sum(a.Miles) as total_miles

						FROM walk_2009_stats a, (SELECT @rownum:=0) b

						GROUP BY NUID ORDER BY total_miles DESC";  

						

						$data2 = mysql_query($sql2) or die ("Could not run query: " . $sql2 . "<br />\n" . mysql_error () );

						

						echo'<h3 align="left">Total Milage To Date | Download Here</h3><br/>';

						

						echo "<table border='0' cellpadding='0' cellspacing='1'>";

						echo "

						<tr>

						<td style='text-align:center'><b><u>Rank</b></u></td>

						<td style='text-align:center'><b><u>NUID</b></u></td>

						<td style='text-align:center'><b><u>First Name</b></u></td>

						<td style='text-align:center'><b><u>Last Name</b></u></td>

						<td style='text-align:center'><b><u>Site</b></u></td>

						<td style='text-align:center'><b><u>Milage</b></u></td>

						</tr>";

						

						// THIS SETS UP THE COLOR STYLE FOR EACH ROW, INSIDE THE WHILE LOOP WE WILL ASK THE COLORS TO ALTERNATE

						$style = 0;

						

						// Start rank

						$rank = 1;

						

						while ($results2 = mysql_fetch_assoc($data2)){

						

							//inside the loop change the class of the row/column 

							//(based on a style sheet). you could also directly specify 

							//a background colour here

							if($style == 1) {

							$tclass = "row1";

							$style = 0;

							} else {

							$tclass = "row2";

							$style = 1;

							}

						

						$NUID = $results2['NUID'];

						$Total_Miles = $results2['total_miles'];

						$sql3="SELECT * FROM walk_2009_members WHERE NUID='$NUID' ";

						$data3 = mysql_query($sql3) or die ("Could not run query: " . $sql3 . "<br />\n" . mysql_error () );

						while ($results3 = mysql_fetch_assoc($data3)){

						echo 

						'<tr class="'.$tclass.'" >

						<td style="text-align:center">'.($rank++).'</td>

						<td style="text-align:center">'.$results3['NUID'].'</td>

						<td style="text-align:center">'.$results3['FirstName'].'</td>

						<td style="text-align:center">'.$results3['LastName'].'</td>

						<td style="text-align:center">'.$results3['Site'].'</td>

						<td style="text-align:center">'.$results2['total_miles'].'</td>

						</tr>';

						}
 

						

						}

						echo "</table>";

						 

				  }// END OF GETSUMS IF STATEMENT

				 ?>

Open in new window

0
Comment
Question by:evibesmusic
  • 7
  • 5
14 Comments
 
LVL 39

Expert Comment

by:Roger Baklund
Comment Utility
Yes, it is possible. There are libraries available, for instance:

http://pear.php.net/package/Spreadsheet_Excel_Writer
0
 

Author Comment

by:evibesmusic
Comment Utility
@cxr:

I appreciate the link and the pear package looks nice but, I can't install anything on the host server.

Any other possible ways this might be done via a php script?

EVM
0
 
LVL 39

Expert Comment

by:Roger Baklund
Comment Utility
What do you mean by "formatted", what kind of formatting is needed?

Excel recognize different formats, the simplest method is to write a TAB separated CSV file: separate each field with a TAB character, and separate each row with a newline character. No particular formatting is possible with this method, but excel will right-align numbers and left-align text. Something like this:
<?php
 

mysql_connect('localhost','user','pass');

mysql_select_db('dbname');

$result = mysql_query('select * from MyTable');
 

$filename = 'excelfile.xls';
 

header("Content-type: application/octet-stream");

header("Content-Disposition: attachment; filename=$filename");

header("Pragma: no-cache");

header("Expires: 0");
 

$quote = create_function('$item',

  'return str_replace(array("\r",\'"\'),array("",\'""\'), $item);');
 

$firstrow = true;

while($row = mysql_fetch_assoc($result)) {

  if($firstrow) {

    echo implode("\t",array_map($quote,array_keys($row)))."\n";

    $firstrow = false;

  }

  echo implode("\t",array_map($quote,$row))."\n";

}
 

?> 

Open in new window

0
 

Author Comment

by:evibesmusic
Comment Utility
@cxr:

Sorry for using the word 'formatted', I just basically want the information placed into a spreadsheet according to column heading within the database.  If what you have described above will do this then I am set.  Thank you for your attention to this question.

EVM
0
 
LVL 39

Accepted Solution

by:
Roger Baklund earned 500 total points
Comment Utility
Try this, then:
<?php
 

mysql_connect('localhost','user','pass');

mysql_select_db('dsadb2');
 

mysql_query('SET @rownum:=0');
 

$sql = "SELECT 

    @rownum:=@rownum + 1 'Rank',

    a.NUID, FirstName 'First Name', LastName 'Last Name', Site, 

    sum(a.Miles) as Mileage

  FROM walk_2009_stats a, walk_2009_members b

  WHERE a.NUID=b.NUID

  GROUP BY a.NUID, FirstName, LastName, Site

  ORDER BY Mileage DESC";

$result = mysql_query($sql);

if(!$result) die(mysql_error());
 

$filename = 'Mileage_'.date('Y-m-d').'.xls';
 

header("Content-type: application/octet-stream");

header("Content-Disposition: attachment; filename=$filename");

header("Pragma: no-cache");

header("Expires: 0");
 

$quote = create_function('$item',

  'return str_replace(array("\r",\'"\'),array("",\'""\'), $item);');
 

$firstrow = true;

while($row = mysql_fetch_assoc($result)) {

  if($firstrow) {

    echo implode("\t",array_map($quote,array_keys($row)))."\n";

    $firstrow = false;

  }

  echo implode("\t",array_map($quote,$row))."\n";

}
 

?>

Open in new window

0
 

Author Comment

by:evibesmusic
Comment Utility
@cxr:

Sorry for the long delay.  I've placed your code inside of my page and it produces all of the results of the query but, prints them to the screen.

Can you offer any other suggestions on how to get the results of the query to populate an Excell spreadsheet?
0
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
LVL 39

Expert Comment

by:Roger Baklund
Comment Utility
>> I've placed your code inside of my page

That is wrong, it should be saved as a separate php script. When this script is executed, it should load in excel automatically.
0
 

Author Comment

by:evibesmusic
Comment Utility
@cxr:

Thank you for correcting my implementation of your script.  The script now works but, all of the information in the db is placed into the contents of one cell in the spreadsheet.  Is it possible to have all of the db contents populate the spreadsheet just like in the db itself (with column headers, followed by the data)?
0
 
LVL 39

Expert Comment

by:Roger Baklund
Comment Utility
That is what it was supposed to do, and it does so on my computer...

Try modifying the file extension, change this:

$filename = 'Mileage_'.date('Y-m-d').'.xls';

...into this:

$filename = 'Mileage_'.date('Y-m-d').'.csv';
0
 

Author Comment

by:evibesmusic
Comment Utility
@cxr:

When I changed the coding per your last post, it placed each row of db values into one cell.  It did not seperate the results into different colums.

Would the version of Excell have any affect on how the information is displayed?  I am using MS Excell 2003.  Hmmm....

I have also modified the name of the file that is downloaded as you can see by the files below.
Total-Mileage-DB-As-of2009-07-23.csv
Mileage-2009-07-23.xls
0
 
LVL 39

Expert Comment

by:Roger Baklund
Comment Utility
I found the code below at the start of the files. It should not be there, it is not produced by the code I posted in http:#a24843720

You should use my code as is, without inserting HTML headers at the beginning.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>Untitled Document</title>

</head>
 

<body>

Open in new window

0
 
LVL 39

Expert Comment

by:Roger Baklund
Comment Utility
My answer http:#a24843720 was correct, the asker inserted html headers, which brakes it. I explained that in http:#a24931134.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

A little background as to how I came to I design this code: Around 5 years ago I designed an add-in that formatted Excel files to a corporate standard, applying different cell colours and font type depending on whether the cells contained inputs,…
Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
This Micro Tutorial demonstrate the bugs in Microsoft Excel for Mac with Pivot Charts.
This Micro Tutorial demonstrates in Microsoft Excel how to consolidate your marketing data by creating an interactive charts using form controls. This creates cool drop-downs for viewers of your chart to choose from.

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now