如果您的 MySQL 数据在 Excel 单元格中未正确对齐,其中多行的数据最终位于单个单元格中,以下是解决此问题的方法问题:
提供的 PHP 脚本需要进行一些修改才能正确处理多行。这是修改后的代码:
<?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);
以上是使用 PHP 导出到 Excel 时如何修复 MySQL 数据对齐问题?的详细内容。更多信息请关注PHP中文网其他相关文章!