Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

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

Posted on 2009-07-07
14
Medium Priority
?
357 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
12 Comments
 
LVL 39

Expert Comment

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

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

Author Comment

by:evibesmusic
ID: 24807949
@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
ID: 24809893
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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:evibesmusic
ID: 24842601
@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 2000 total points
ID: 24843720
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
ID: 24930302
@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
 
LVL 39

Expert Comment

by:Roger Baklund
ID: 24930340
>> 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
ID: 24930607
@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
ID: 24930756
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
ID: 24930973
@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
ID: 24931134
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
ID: 25105614
My answer http:#a24843720 was correct, the asker inserted html headers, which brakes it. I explained that in http:#a24931134.
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article describes how you can use Custom Document Properties to store settings and other information in your workbook so that they will be available the next time you open the workbook.
In this blog, we’ll look at how improvements to Percona XtraDB Cluster improved IST performance.
This Micro Tutorial will demonstrate how to create pivot charts out of a data set. I also added a drop-down menu which allows to choose from different categories in the data set and the chart will automatically update.
In this video, Percona Solution Engineer Rick Golba discuss how (and why) you implement high availability in a database environment. To discuss how Percona Consulting can help with your design and architecture needs for your database and infrastr…
Suggested Courses

877 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