Solved

Problem with Export to Excel in PHP

Posted on 2008-10-11
8
2,166 Views
Last Modified: 2013-12-13
I am having trouble with how the excel file looks once it gets exported. The exported excel file displays all the content in a single cell. In other words, all of the columns and rows in the MySQL table I am exporting just get dumped into a single excel cell. It seems that the "\t" and "\n" characters are simply being ignored during export. I am attaching the code I am using to generate the export. What am I doing wrong?
<?php
// Start output buffering.
ob_start();
// Initialize a session.
session_start();
?>
<!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>Transitions Survey Database Export Page</title>
</head>
<body>
<?php 
if (isset($_SESSION['adminid'])) {
 
       // Connect to the database.
	
	$select = "SELECT * FROM reginfo";
	
	$export = mysql_query ( $select ) or die ( "Sql error : " . mysql_error( ) );
	
	$fields = mysql_num_fields ( $export );
	
	for ( $i = 0; $i < $fields; $i++ )
	{
		$header .= mysql_field_name( $export , $i ) . "\t";
	}
	
	while( $row = mysql_fetch_row( $export ) )
	{
		$line = '';
		foreach( $row as $value )
		{                                            
			if ( ( !isset( $value ) ) || ( $value == "" ) )
			{
				$value = "\t";
			}
			else
			{
				$value = str_replace( '"' , '""' , $value );
				$value = '"' . $value . '"' . "\t";
			}
			$line .= $value;
		}
		$data .= trim( $line ) . "\n";
	}
	$data = str_replace( "\r" , "" , $data );
	
	if ( $data == "" )
	{
		$data = "\n(0) Records Found!\n";                        
	}
	
	header("Content-type: application/octet-stream");
	header("Content-Disposition: attachment; filename=survey_results.xls");
	header("Pragma: no-cache");
	header("Expires: 0");
	print "$header\n$data";
 
} else {
	echo "You are not authorized to view this page.";
}
?>
</body>
</html>
<?php // Flush the buffered output.
ob_flush();
?>

Open in new window

0
Comment
Question by:Liquid_Inc
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
8 Comments
 
LVL 2

Assisted Solution

by:shellghost
shellghost earned 200 total points
ID: 22695739
Not sure if this will help, but in my experience, when I want to export something to "Excel" I have had the best luck generating comma delimited values and writing to a .csv file.  If configured to do so (by default it is), Excel will open a .cdv file and you can go from there.  I don't know what to do about the \t and \n problem.  Hope that helps!
0
 
LVL 12

Expert Comment

by:jazzIIIlove
ID: 22695967
I had done this before...But now, i am trying on your code and for 15 minutes, i got the same problem of yours...
<?php
// Start output buffering.
ob_start();
// Initialize a session.
session_start();
?>
 
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Transitions Survey Database Export Page</title>
</head>
<body>
<?php 
$_SESSION['adminid'] = "baran";
if (isset($_SESSION['adminid'])) {
 
       // Connect to the database.
    $dbConnLink = mysql_connect("localhost", "root", "root");   
    mysql_select_db(alumni, $dbConnLink);  
    $select = "SELECT * FROM alumni_year";
    
    $export = mysql_query ( $select ) or die ( "Sql error : " . mysql_error( ) );
    
                             $header = "First Field" . "\t". "Second Field" .  "\r\n";                            
                        while ($row = mysql_fetch_assoc($export)) {                            
                            $data .= $row['ID'] . "\t" . $row['year'] .  "\r\n";
                        }
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=searchresults.xls");
header("Pragma: no-cache");
header("Expires: 0");
echo $header."\n".$data;
 
} else {
    echo "You are not authorized to view this page.";
}
 
 
 
?>
</body>
</html>

Open in new window

0
 
LVL 12

Expert Comment

by:jazzIIIlove
ID: 22695970
I will find it...
0
Technology Partners: 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!

 
LVL 12

Expert Comment

by:jazzIIIlove
ID: 22695995
damn...i had done that before...OK...I am doing it with PEAR!
0
 
LVL 12

Expert Comment

by:jazzIIIlove
ID: 22696102
Yes, i did it with PEAR...

google for PEAR classes to include if you don't have one...

If you can't find, i will send it to you!
dummy.php:
<?
  echo "<p><a href='./sql2excel.php'>Generate XLS file</a></p>";
?>
*************************
 
<?php
// Start output buffering.
    include_once "./Spreadsheet/Excel/Writer.php";
// Initialize a session.
session_start();
?>
 
<html>
<head> Yeah! </head>
<body>
<?php 
$_SESSION['adminid'] = "baran";
if (isset($_SESSION['adminid'])) {
 
       // Connect to the database.
    $dbConnLink = mysql_connect("localhost", "root", "root");   
    mysql_select_db(alumni, $dbConnLink);  
    $select = "SELECT * FROM alumni_year";
    
    $export = mysql_query ($select);
    /*
    $xls =& new Spreadsheet_Excel_Writer("aaa.xls");
    $xls->send("test.xls");
    $format =& $xls->addFormat();
    $format->setBold();
    $format->setColor("blue");
    $sheet =& $xls->addWorksheet('Test XLS');
    $sheet->write(0, 0, 1, 0);
    $sheet->write(0, 1, 2, 0);
    $sheet->writeString(1, 0, "XAMPP:", 0);
    $sheet->writeString(1, 1, 12, $format);
    $xls->close();
    
    echo "ok";
    */
    $rowCount = mysql_num_rows($export);
    $xls =& new Spreadsheet_Excel_Writer("fuck.xls");   
    //$xls->send("fucking.xls");
    $format =& $xls->addFormat();
    $format->setBold();
    $format->setColor("blue");
    $sheet =& $xls->addWorksheet('SQL to Fucking XLS');
          $i=0;
while ($row = mysql_fetch_assoc($export)){                                                               
    $sheet->write(0, 0, "ID", 0);
    $sheet->write(0, 1, "Year", 0);
    $sheet->writeString($i, 0, $row['ID'] , 0);
    $sheet->writeString($i, 1, $row['year'], $format);
$i++;                
    
}
    
    $xls->close(); 
  
}
 else {
    echo "You are not authorized to view this page.";
}
?>
</body>
</html>

Open in new window

0
 
LVL 12

Accepted Solution

by:
jazzIIIlove earned 300 total points
ID: 22696117
<<I am attaching the code I am using to generate the export. What am I doing wrong?

Nothing wrong, you have done...I really tried everything i can on your code but i cannot do with your way, but PEAR way...If you want, you can extract the functions from PEAR and use them as your need...
dummy.php:
<?
  echo "<p><a href='./sql2excel.php'>Generate XLS file</a></p>";
?>
*************************
 
<?php
// Start output buffering.
    include_once "./Spreadsheet/Excel/Writer.php";
// Initialize a session.
session_start();
?>
 
<html>
<head> Yeah! </head>
<body>
<?php 
$_SESSION['adminid'] = "baran";
if (isset($_SESSION['adminid'])) {
 
       // Connect to the database.
    $dbConnLink = mysql_connect("localhost", "root", "root");   
    mysql_select_db(alumni, $dbConnLink);  
    $select = "SELECT * FROM alumni_year";
    
    $export = mysql_query ($select);
    /*
    $xls =& new Spreadsheet_Excel_Writer("aaa.xls");
    $xls->send("test.xls");
    $format =& $xls->addFormat();
    $format->setBold();
    $format->setColor("blue");
    $sheet =& $xls->addWorksheet('Test XLS');
    $sheet->write(0, 0, 1, 0);
    $sheet->write(0, 1, 2, 0);
    $sheet->writeString(1, 0, "XAMPP:", 0);
    $sheet->writeString(1, 1, 12, $format);
    $xls->close();
    
    echo "ok";
    */
    $rowCount = mysql_num_rows($export);
    $xls =& new Spreadsheet_Excel_Writer("fuck.xls");   
    //$xls->send("fucking.xls");
    $format =& $xls->addFormat();
    $format->setBold();
    $format->setColor("blue");
    $sheet =& $xls->addWorksheet('SQL to Fucking XLS');
          $i=0;
while ($row = mysql_fetch_assoc($export)){                                                               
    $sheet->write(0, 0, "ID", 0);
    $sheet->write(0, 1, "Year", 0);
    $sheet->writeString($i, 0, $row['ID'] , 0);
    $sheet->writeString($i, 1, $row['year'], $format);
$i++;                
    
}
    
    $xls->close(); 
  
}
 else {
    echo "You are not authorized to view this page.";
}
?>
</body>
</html>

Open in new window

0
 
LVL 3

Expert Comment

by:wktang83
ID: 22696641
I scanned through your code once. I don't know what went wrong, but try to look at my working code below. This should give you some idea what to modify in order to make it working.
$csv_output = 'Last Name, First Name, User Name, Professor, Score, Submitted, ';
    $num_questions = getTotalQuestions();
    for ($i = 0; $i < $num_questions; $i++)
    {
        $csv_output .= ($i+1);
        if ($i != $num_questions - 1)
        {
            $csv_output .= ',';
        }
    }
    $csv_output .= "\015\012";
    $result = mysql_query("select * from students"); 
 
    while($row = mysql_fetch_array($result)) { 
        $csv_output .= "$row[last_name],$row[first_name],$row[user_name],".getProfLastName($row[prof_id]).",$row[score],$row[last_submitted],$row[answers]";
        $csv_output .="\015\012";
    }
 
    header("Content-type: application/vnd.ms-excel");
    header("Content-disposition: csv; filename= Student_Data_". date("Y-m-d") . ".csv");
    print $csv_output;
    exit;

Open in new window

0
 

Author Closing Comment

by:Liquid_Inc
ID: 31505377
Thank you! I finally have a working export to excel page :)
0

Featured Post

Creating Instructional Tutorials  

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

Question has a verified solution.

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

Suggested Solutions

Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
This article discusses how to implement server side field validation and display customized error messages to the client.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

734 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