使用UTF-8编码将数据从MySQL导出到Excel

时间:2013-06-14 12:13:47

标签: php mysql excel csv

我有一个带有utf8_general_ci排序规则的mysql行,当我将它导出到csv时,而不是正确的utf-8字符我得到Ć…ā€¦I等,如何让excel了解这里的UTF-8编码是我的代码:

$conn = mysql_connect('localhost', 'root', 'asdfggh') or die(mysql_error());
mysql_query("SET CHARACTER SET utf8"); 
mysql_query("SET NAMES utf8"); 
mysql_select_db('table_name', $conn) or die(mysql_error($conn));

$query = sprintf('SELECT * FROM sudraba_birzs');
$result = mysql_query($query, $conn) or die(mysql_error($conn));

header('Content-Encoding: UTF-8');
header('Content-type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename="'.date("d-m-Y_H:i") . '.csv'.'"'); 
echo "\xef\xbb\xbf";

$row = mysql_fetch_assoc($result);
if ($row) {
    echocsv(array_keys($row));
}

while ($row) {
    echocsv($row);
    $row = mysql_fetch_assoc($result);
}

function echocsv($fields)
{
    $separator = '';
    foreach ($fields as $field) {
        if (preg_match('/\\r|\\n|,|"/', $field)) {
            $field = '"' . str_replace('"', '""', $field) . '"';
        }
        echo $separator . $field;
        $separator = ',';
    }
    echo "\r\n";
}

如何导出它以正确显示所有字符(使Excel理解utf-8)并保持表格布局(包含行和列)

3 个答案:

答案 0 :(得分:6)

您正在生成CSV,它基本上是纯文本文件。无法在此类文件中指定编码信息。大多数文本编辑器实现(更好或更差)编码自动检测。 Excel没有。当您右键单击CSV文件时,Excel将简单地假设ANSI。 (您需要使用“打开”菜单才能获得有关编码的提示。)

您唯一的选择(除了切换到另一种输出格式)是将数据转换为ANSI,使用mb_convert_encoding()iconv()。但现在你有另一个问题:ANSI不是真正的编码,它基本上意味着“在我的 Windows计算机中设置的任何编码”。首先,您必须找出大多数用户的典型编码。这主要取决于国家。例如,许多西欧国家使用Win-1252。

答案 1 :(得分:2)

我遇到了同样的问题(使用西班牙语的数据库中的常见问题)。我写了这个并且它有效:

这是一个与数据库连接的类,函数将使用mysqli和PHP执行任何操作。在这种情况下,调用此类(require或include),只需使用" downloadCsv()"功能

作为一个例子,这将是" class.php"文件:

<?php
class DB{

private $con;

//this constructor connects with the database
public function __construct(){
$this->con = new mysqli("Your_Host","Your_User","Your_Pass","Your_DatabaseName");

if($this->con->connect_errno > 0){
    die('There was a problem [' . $con->connect_error . ']');
    }
}

//create the function that will download a csv file from a mysqli query

public function downloadCsv(){

$count = 0;
$header = "";
$data = "";
//query
$result = $this->con->query("SELECT * FROM Your_TableName");
//count fields
$count = $result->field_count;
//columns names
$names = $result->fetch_fields();
//put column names into header
foreach($names as $value) {
    $header .= $value->name.";";
    }
}
//put rows from your query
while($row = $result->fetch_row())  {
    $line = '';
    foreach($row as $value)       {
        if(!isset($value) || $value == "")  {
            $value = ";"; //in this case, ";" separates columns
    } else {
            $value = str_replace('"', '""', $value);
            $value = '"' . $value . '"' . ";"; //if you change the separator before, change this ";" too
        }
        $line .= $value;
    } //end foreach
    $data .= trim($line)."\n";
} //end while
//avoiding problems with data that includes "\r"
$data = str_replace("\r", "", $data);
//if empty query
if ($data == "") {
    $data = "\nno matching records found\n";
}
$count = $result->field_count;

//Download csv file
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=FILENAME.csv");
header("Pragma: no-cache");
header("Expires: 0");
echo $header."\n".$data."\n";

}
?>

创建&#34; class.php&#34;在这个例子中,文件使用&#34; download.php&#34;文件:

<?php
//call the "class.php" file
require_once 'class.php';
//instantiate DB class
$export = new DB();
//call function
$export->downloadCsv();
?>

下载后,使用MS Excel打开文件。

我希望这对你有帮助,我想我写得很好,我对文本和代码字段感到不舒服。

答案 2 :(得分:0)

作为替代和大量的sipmler解决方案,您可以试试这个,我现在使用它已经有几年了,并且从未遇到过问题。

db_connect.php

<?php
$mysqli = new mysqli($mysqli_host, $mysqli_user, $mysqli_pass, $mysqli_db);
if ($mysqli->connect_errno)
    {
    $debug = $debug.'<br/>Failed to connect to MySQL: (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error;
    }
else
    {
    $debug = $debug.'<br/>Connected to '. $mysqli->host_info;
    }
?>

导出功能

function export($query_exp,$name)
    {
    require '../lib/db_config.php';
    require '../lib/db_connect.php';

    $filename = $name.' - '.date('Y.m.d').'.xls'; /*set desired output file name here*/

    function cleanData(&$str)
                {
                    $str = preg_replace("/\t/", "\\t", $str);
                    $str = preg_replace("/\r?\n/", "\\n", $str);
                    if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
                    if ($str=='') {$str='-';}
                }

    header("Content-Disposition: attachment; filename=\"$filename\"");
    header("Content-Type: application/vnd.ms-excel");

    $flag = false;

    if ($result = $mysqli->query($query_exp))
            {
            if ($result->num_rows>0)
                {
                $result->data_seek(0);
                while ($row = $result->fetch_assoc())
                    {
                    if(!$flag)
                        {
                        print implode("\t", array_keys($row)) . "\r\n";
                        $flag = true;
                        }
                    array_walk($row, 'cleanData');
                    print implode("\t", array_values($row)) . "\r\n";
                    }
                }
            else { $debug = $debug.'<br/>Empty result'; /*DEBUG*/ }
            }
    else { $debug = $debug.'<br/>Oups, Query error!<br/>Query: '.$query_exp.'<br/>Error: '.$mysqli->error.'.'; /*DEBUG*/ }

    require '../lib/db_disconnect.php';
    }

您可以将该功能称为:

export('SELECT * FROM SAMPLE WHERE 1;','desired_file_name.extension')