2

csvにエクスポートすると、照合のあるmysql行があり、utf8_general_ci取得した正しいutf-8文字の代わりに、Å…IExcelに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 を理解できるようにする) と、テーブルのレイアウトも維持する方法 (行と列を使用)

4

3 に答える 3

6

基本的にプレーンテキストファイルである CSV を生成しています。このような種類のファイルでエンコーディング情報を指定する方法はありません。ほとんどのテキスト エディターは、(良くも悪くも) エンコードの自動検出を実装しています。エクセルにはありません。CSV ファイルを右クリックすると、Excel は単純に ANSI を想定します。(エンコードに関するプロンプトを表示するには、[開く] メニューを使用する必要があります。)

(別の出力形式への切り替えを除いて)残された唯一のオプションは、mb_convert_encoding()またはiconv()を使用して、データを ANSI に変換することです。しかし、ここで別の問題が発生します。ANSI は実際のエンコーディングではなく、基本的に「Windows コンピュータで設定されているエンコーディング」を意味します。最初に、ほとんどのユーザーが使用している典型的なエンコーディングを見つける必要があります。それは主に国に依存します。たとえば、西ヨーロッパの多くの国では Win-1252 が使用されています。

于 2013-06-14T12:23:50.700 に答える
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";

}
?>

「class.php」ファイルを作成した後、この例では、「download.php」ファイルでその関数を使用します。

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

ダウンロード後、MS Excel でファイルを開きます。

これがあなたの助けになることを願っています。私はそれをうまく書いたと思います。私はテキストとコードフィールドに慣れていませんでした。

于 2013-12-20T09:15:37.970 に答える
0

代替のよりシンプルなソリューションとして、これを試すことができます。私は今までに数年間使用していますが、問題はありませんでした。

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')
于 2013-06-14T15:19:20.947 に答える