MySQL到.XLS编码问题

时间:2013-01-22 19:12:11

标签: php mysql excel encoding xls

我将数据从 MySQL 传输到 .XLS 文件时遇到编码问题。表格位于 UTF-8 中的“ utf8_czech_ci ”和 PHP 脚本中。我总是得到“ěščřžýáíé”这样的字符,形状像“Ä>Å¡ÅřžýáÃÔ。有我的脚本

<?php

mb_http_input("utf-8");
mb_http_output("utf-8");

     $dbhost  = "XXXXXXXXXXX";
     $dbuser  = "XXXXXXXXXXX";
     $dbpass  = "XXXXXXXXXXX";
     $dbname  = "XXXXXXXXXXX";
     $dbtable = $_GET['table'];

function xlsBOF() {
    echo pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0);
    return;
}

function xlsEOF() {
    echo pack("ss", 0x0A, 0x00);
    return;
}

function xlsWriteLabel($Row, $Col, $Value ) {
    $L = strlen($Value);
    echo pack("ssssss", 0x204, 8 + $L, $Row, $Col, 0x0, $L);
    echo $Value;
    return;
}

$dbc = mysql_connect( $dbhost , $dbuser , $dbpass ) or die( mysql_error() );
mysql_query("set names utf8;");
mysql_select_db( $dbname );
$q = "SELECT * FROM ".$dbtable."";
$qr = mysql_query( $q ) or die( mysql_error() );

header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-type: application/vnd.ms-excel; charset=utf-8");
header("Content-Disposition: attachment;filename=export_".$dbtable.".xls ");
header("Content-Transfer-Encoding: binary ");
xlsBOF();

$col = 0;
$row = 0;
$first = true;

while( $qrow = mysql_fetch_assoc( $qr ) )
{
    if( $first )
    {
        foreach( $qrow as $k => $v )
        {
            xlsWriteLabel( $row, $col, strtoupper( ereg_replace( "_" , " " , $k ) ) );
            $col++;
        }
        $col = 0;
        $row++;
        $first = false;
    }
    foreach( $qrow as $k => $v )
    {
        xlsWriteLabel( $row, $col, $v );
        $col++;
    }

    $col = 0;
    $row++;
}

xlsEOF();
exit();

感谢您的回复......

1 个答案:

答案 0 :(得分:0)

Excel文件使用代码页块来标识文件中使用的字符集,但默认情况下它将使用区域设置代码页。如果你想强制使用UTF-8,那么你还需要编写一个UTF-8代码页块

$record          = 0x0042;   // Record identifier
$length          = 0x0002;   // Number of bytes to follow
$cv              = 0x04B0;   // The UTF-8 code page

$header          = pack('vv', $record, $length);
$data            = pack('v',  $cv);