I am trying to generate an XLS file from a table in a MySQL database, but the Excel file is not formatted properly and an Excel file is generated when an error occurs. "The file you are trying to open is in a different format than the one indicated." When a file is opened, the data is not formatted properly.
Any ideas what I am missing?
<?php $host = 'XXXXXXX'; $dbname = 'XXXXXXXX'; $username = 'XXXXXXXX'; $password = 'XXXXXXXX'; function xlsBOF() { echo pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0); return; } function xlsEOF() { echo pack("ss", 0x0A, 0x00); return; } function xlsWriteLabel($Row, $Col, $Value ) { $L = strlen($Value); echo pack("ssssss", 0x204, 8 + $L, $Row, $Col, 0x0, $L); echo $Value; return; } function xlsWriteNumber($Row, $Col, $Value) { echo pack("sssss", 0x203, 14, $Row, $Col, 0x0); echo pack("d", $Value); return; } try { $conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password); echo "Connected to $dbname at $host successfully."; $conn = null; } catch (PDOException $pe) { die("Could not connect to the database $dbname :" . $pe->getMessage()); } $q = "SELECT * FROM tablename"; $qr = mysql_query( $q ) or die( mysql_error() ); 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"); header("Content-Disposition: attachment;filename=export_".$dbtable.".xls "); header("Content-Transfer-Encoding: binary "); xlsBOF(); $col = 0; $row = 0; $first = true; while( $qrow = mysql_fetch_assoc( $qr ) ) { if( $first ) { foreach( $qrow as $k => $v ) { xlsWriteLabel( $row, $col, strtoupper( ereg_replace( "_" , " " , $k ) ) ); $col++; } $col = 0; $row++; $first = false; }
Dipak saraf
source share