2016-07-12 68 views
0

我試圖用UTF-8編碼在excel中保存mysql數據。但所有數據保存在一個單元格中。但我有Excel文件的問題。它顯示UTF-8字符很難看。在excel中導出mysql utf 8數據

Excel文件: this is output

DB連接:

<?php 
$conn=mysql_connect("localhost","root","") or die("Could not connect"); 
mysql_select_db("urulikanchan",$conn) or die("could not connect database"); 
mysql_set_charset('utf8',$conn); 
mysql_query("SET NAMES utf8"); 
?> 

EXCEL文件下載:

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="utf-8"> 
    <title>New Post</title> 


</head> 
<body> 
<?php 


include 'db.php'; 

$SQL = "SELECT * from member_detail"; 
$header = ''; 
$result =''; 
$exportData = mysql_query ($SQL) or die ("Sql error : " . mysql_error()); 

$fields = mysql_num_fields ($exportData); 

for ($i = 0; $i < $fields; $i++) 
{ 
    $header .= mysql_field_name($exportData , $i) . "\t"; 
} 

while($row = mysql_fetch_row($exportData)) 
{ 
    $line = ''; 
    foreach($row as $value) 
    {            
     if ((!isset($value)) || ($value == "")) 
     { 
      $value = "\t"; 
     } 
     else 
     { 
      $value = str_replace('"' , '""' , $value); 
      $value = '"' . $value . '"' . "\t"; 
     } 
     $line .= $value; 
    } 
    $result .= trim($line) . "\n"; 
} 
$result = str_replace("\r" , "" , $result); 

if ($result == "") 
{ 
    $result = "\nNo Record(s) Found!\n";       
} 

header("Content-type: application/octet-stream"); 
header("Content-Disposition: attachment; filename=export.xls"); 
header("Pragma: no-cache"); 
header("Expires: 0"); 

header('Content-Encoding: UTF-8'); 

echo "\xEF\xBB\xBF"; 


print "$header\n$result"; 

?> 
    </body></html> 
+0

也許你知道,但: ,它必須得到excel文件?您可以嘗試保存可以在Excel或Open Office中打開的.csv文件,您可以在http://www.w3schools.com/php/func_filesystem_fputcsv.asp或http://code.stephenmorley.org/中查看。 php/creating-downloadable-csv-files/ – uelordi

+0

這不是您生成的本機格式的Excel文件,只是一個帶有製表符分隔符的csv文件(以及一個糟糕的自制csv文件;至少嘗試使用PHP構建的-in [fputcsv()](http://www.php.net/manual/en/function.fputcsv.php)函數,它將解決一些潛在的問題 –

回答

0

如果要產生真正的excel文件,而不只是CSV請考慮使用一些PHP庫,如PHPExcel

下面是一個使用UTF字符的簡單的代碼示例:

<?php 
require_once dirname(__FILE__) . '/PHPExcel/Classes/PHPExcel.php'; 

$objPHPExcel = new PHPExcel(); 
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20); 
$objPHPExcel->getActiveSheet()->setCellValue('A1', 'Test UTF8 Characters:'); 
$objPHPExcel->getActiveSheet()->setCellValue('B1', 'éçà'); 
$objPHPExcel->getActiveSheet()->setTitle('Export'); 
$objPHPExcel->setActiveSheetIndex(0); 
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007'); 


header("Content-type: application/octet-stream"); 
header("Content-Disposition: attachment; filename=export.xlsx"); 
header("Pragma: no-cache"); 
header("Expires: 0"); 
header('Content-Encoding: UTF-8'); 

$objWriter->save('php://output');