NVH’s Blog

January 8, 2007

Thủ thuật tạo file CSV chứa dữ liệu unicode hiển thị đúng trên Excel

Filed under: hoc tap

Thủ thuật tạo file CSV chứa dữ liệu unicode hiển thị đúng trên Excel
Bài toán: export dữ liệu tiếng Việt UTF-8 thành file CSV có thể hiển thị đúng khi mở bằng Excel.
3 điểm dẫn đến thành công:
+ Dùng TAB (\t) thay cho COMMA (,) để phân tách các cột
+ Convert Encoding của dữ liệu cần output bằng UTF-16LE
+ Gắn chr(255)chr(254) vào đầu của kết quả cuối cùng trước khi output
Code demo cho PHP
// khai báo $filepath
// tạo nội dung $tmp
// convert và output
$tmp = chr(255).chr(254).mb_convert_encoding($tmp, ‘UTF-16LE’, ‘UTF-8′);
$write = fwrite($filepath, $tmp);
Địa chỉ tham khảo: http://www.php.net/fwrite

Môi trường phát triển khi thực hiện:
+ DB: Postgres 8.x
+ WebServer: Apache 2.0.x
+ Engine: PHP 5.4.x
+ Excel 2003

Kết quả:

+ ngòai kết quả cần đạt được là hiển thị đúng tiếng Việt, dữ liệu tiếng Nhật cũng hiển thị đúng.

5 Comments »

The URI to TrackBack this entry is: http://hungnv.blogsome.com/2007/01/08/p92/trackback/

  1. Anh ơi ! Hiện tại em đang gặp khó khăn trong việc export dữ liệu từ MySQL sang Excel bằng PHP script với lý do dữ liệu ghi ra bị lỗi font xuất hiện dấu “?”. Anh vui lòng tư vấn giúp em kỹ thêm về vấn đề này được không ? Code của em đây

    ” . mysql_error() . “” . mysql_errno());
    //select database
    $Db = @mysql_select_db($DB_DBName, $Connect)
    or die(”Couldn’t select database:” . mysql_error(). “” . mysql_errno());

    //@mysql_query(”SET SESSION character_set_server=utf8″,$Connect) or die(”Couldn’t set character_set_server:” . mysql_error(). “” . mysql_errno());
    @mysql_query(”SET NAMES ‘utf8′”,$Connect) or die(”Couldn’t set names:” . mysql_error(). “” . mysql_errno());
    //@mysql_query(”SET CHARACTER SET ‘utf8′”,$Connect);
    //execute query
    $result = @mysql_query($sql,$Connect)
    or die(”Couldn’t execute query:” . mysql_error(). “” . mysql_errno());
    //if this parameter is included ($w=1), file returned will be in word format (’.doc’)
    //if parameter is not included, file returned will be in excel format (’.xls’)
    if (isset($w) && ($w==1))
    {
    $file_type = “msword;”;
    $file_ending = “doc”;
    }else {
    $file_type = “vnd.ms-excel;”;
    $file_ending = “xls”;
    }
    //header info for browser: determines file type (’.doc’ or ‘.xls’)
    header(”Content-Type: application/$file_type; charset=utf8″);
    header(”Content-Disposition: attachment; filename=database_dump.$file_ending”);
    header(”Pragma: no-cache”);
    header(”Expires: 0″);

    /* Start of Formatting for Word or Excel */

    if (isset($w) && ($w==1)) //check for $w again
    {
    /* FORMATTING FOR WORD DOCUMENTS (’.doc’) */
    //create title with timestamp:
    if ($Use_Title == 1)
    {
    echo(”$titlenn”);
    }
    //define separator (defines columns in excel & tabs in word)
    $sep = “n”; //new line character

    while($row = mysql_fetch_row($result))
    {
    //set_time_limit(60); // HaRa
    $schema_insert = “”;
    for($j=0; $j

    Comment by AmThamYeuEm — September 13, 2007 @ 1:59 pm

  2. Cảm ơn anh, em đang gặp vấn đề với việc export Unicode string ra file CSV. Nhờ có bài viết này em đã giải quyết được rồi ^^

    Comment by Đỗ Nam Khánh — August 6, 2008 @ 10:41 am

  3. thanks nhìu…

    Comment by chuotyeugao — September 27, 2008 @ 5:11 am

  4. đây là đoạn code em làm mà kô hiểu sao nó lại cứ kô được, thiệt là khổ quá đi.

    global $header,$export;
    while($row = mysql_fetch_row($export)) //tra ve theo thu tu cac cot neu dung mysql_fetch_array thi tra ve hai cach ;a ten field va thu tu cua field luon
    {
    $line = ‘’;
    foreach($row as $value)
    {
    $value = mb_convert_encoding($value,”UTF-8″);
    if ((!isset($value)) OR ($value == “”))
    {
    $value = “t”;
    }
    else
    {
    $value = str_replace(’”‘, ‘”"‘, $value);
    $value = ‘”‘ . $value . ‘”‘ . “t”;
    }
    $line .= $value;
    }
    $data .=$line.”n”;
    }
    if ($data == “”)
    {
    $data = “n(0) Records Found!n”;
    }
    $data = chr(255).chr(254).mb_convert_encoding($data, “UTF-16LE”, “UTF-8″);
    header(”Content-type: application/octet-stream”);
    header(”Content-Type: application/.xls; charset=utf-8″);
    // header(”Content-type: application/x-msdownload”);
    header(”Content-disposition: data; filename=” . date(”Y-m-d”) .
    “_order_list.xls;”);

    echo “$headern$data”;

    Comment by nguyễn xuân nghĩa — December 1, 2008 @ 5:11 am

  5. không biết là sai chỗ nào nữa.

    Comment by nguyễn xuân nghĩa — December 1, 2008 @ 5:12 am

RSS feed for comments on this post.

Leave a comment

Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>























Get free blog up and running in minutes with Blogsome
Theme designed by Hadley Wickham