If your MySQL data is not aligning correctly in Excel cells, where multiple rows of data end up in a single cell, here's how to resolve this issue:
The provided PHP script requires a few modifications to handle multiple rows correctly. Here's the revised code:
<?php // Database connection details $DB_Server = "localhost"; $DB_Username = "username"; $DB_Password = "password"; $DB_DBName = "databasename"; $DB_TBLName = "tablename"; $filename = "exportfile"; // File name // Create MySQL connection $Connect = @mysql_connect($DB_Server, $DB_Username, $DB_Password) or die("Couldn't connect to MySQL: " . mysql_error() . "<br>" . mysql_errno()); // Select database $Db = @mysql_select_db($DB_DBName, $Connect) or die("Couldn't select database: " . mysql_error() . "<br>" . mysql_errno()); // Execute query $sql = "SELECT username, password, fullname FROM ecustomer_users WHERE fk_customer='$fk_customer'"; $result = @mysql_query($sql, $Connect) or die("Couldn't execute query: " . mysql_error() . "<br>" . mysql_errno()); // Header info for browser header("Content-Type: application/xls"); header("Content-Disposition: attachment; filename=$filename.xls"); header("Pragma: no-cache"); header("Expires: 0"); // Start formatting for Excel $sep = "\t"; // Tabbed character // Print column names for ($i = 0; $i < mysql_num_fields($result); $i++) { echo mysql_field_name($result, $i) . $sep; } echo "\n"; // Start while loop to get data while ($row = mysql_fetch_row($result)) { $schema_insert = ""; for ($j = 0; $j < mysql_num_fields($result); $j++) { if (!isset($row[$j])) { $schema_insert .= "NULL" . $sep; } elseif ($row[$j] != "") { $schema_insert .= "$row[$j]" . $sep; } else { $schema_insert .= "" . $sep; } } $schema_insert = str_replace($sep . "$", "", $schema_insert); $schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert); $schema_insert .= "\t"; print(trim($schema_insert)); print "\n"; } mysql_close($Connect);
The above is the detailed content of How to Fix MySQL Data Alignment Issues When Exporting to Excel using PHP?. For more information, please follow other related articles on the PHP Chinese website!