如果您的 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中文網其他相關文章!