View Full Version : Export from mysql to Excel. Encoding problem.

09-07-2009, 09:34 PM
Hi there, I have a problem with xls exporting. I use utf8 encoding in mysql and these characters don't appear properly in the exported xls file.

The code is


$dbtable = $_POST['lessons'];

// This one makes the beginning of the xls file
function xlsBOF() {
echo pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0);

// This one makes the end of the xls file
function xlsEOF() {
echo pack("ss", 0x0A, 0x00);

// this will write text in the cell you specify
function xlsWriteLabel($Row, $Col, $Value ) {
$L = strlen($Value);
echo pack("ssssss", 0x204, 8 + $L, $Row, $Col, 0x0, $L);
echo $Value;

// make the connection an DB query
//connect to sql
mysql_connect("localhost","root","") or die (mysql_error());
//bazoume tous xarakthres se utf8 gia na katalabainei ellhnika
mysql_query("set names 'utf8'");
//connect to db
mysql_select_db('subsc') or die (mysql_error());
$q = "SELECT * FROM ".$dbtable." ORDER BY Semester ASC";
$qr = mysql_query( $q ) or die( mysql_error() );

// Ok now we are going to send some headers so that this
// thing that we are going make comes out of browser
// as an xls file.
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");

//this line is important its makes the file name
header("Content-Disposition: attachment;filename=export_".$dbtable.".xls ");

header("Content-Transfer-Encoding: binary ");

// start the file

// these will be used for keeping things in order.
$col = 0;
$row = 0;

// This tells us that we are on the first row
$first = true;

while( $qrow = mysql_fetch_assoc( $qr ) )
// Ok we are on the first row
// lets make some headers of sorts
if( $first )
foreach( $qrow as $k => $v )
// take the key and make label
// make it uppper case and replace _ with ' '
xlsWriteLabel( $row, $col, strtoupper( ereg_replace( "_" , " " , $k ) ) );

// prepare for the first real data row
$col = 0;
$first = false;

// go through the data
foreach( $qrow as $k => $v )
// write it out
xlsWriteLabel( $row, $col, $v );
// reset col and goto next row
$col = 0;



I tried using an utf8 application header with no luck...
Any clues?

Thank you.