Solved

Problem with Export to Excel in PHP

Posted on 2008-10-11
8
2,143 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
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
 
LVL 12

Expert Comment

by:jazzIIIlove
ID: 22695995
damn...i had done that before...OK...I am doing it with PEAR!
0
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

 
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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

This article will explain how to display the first page of your Microsoft Word documents (e.g. .doc, .docx, etc...) as images in a web page programatically. I have scoured the web on a way to do this unsuccessfully. The goal is to produce something …
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
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…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…

757 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

20 Experts available now in Live!

Get 1:1 Help Now