通过PHP将Mysql表数据导出到Excel:数据在Excel中无法正常显示

时间:2015-08-05 17:56:00

标签: php excel csv

我需要从Mysql表“tblinfoaanvraag”导出数据(请参阅此处查看表格的图片:http://s29.postimg.org/qeqp43z4n/mysql.png

我有一个正确查询的工作代码,它触发Excel下载,数据在文件中。但是,Excel文件中的数据仍然格式化为sql查询结果,标题(字段名称)仅显示为“数组”。

所以我现在正在努力解决两件事:将sql-results格式化为.csv文件中的单元格,并且应该正确显示headers / table字段名称,而不仅仅是“Array”。

以下是下载的Excel文件的屏幕截图:http://s13.postimg.org/p0rcehehj/excel1.png

代码:

<?php

if(isset($_POST['InfoaanvragenDownloaden']))
{
    try 
{
// Variables for later use      
    $header="";
    $data="";

//connection
    $sHost = "localhost";
    $sUser = "root";
    $sPassword = "";
    $sDatabase = "corbati";
    $link = @mysqli_connect($sHost, $sUser, $sPassword, $sDatabase) or die("Oop, dbase is gone!");

//create query to select as data from your table
$select = "select * from tblinfoaanvraag ORDER BY PK_Infoaanvraag DESC";

//run mysql query and then count number of fields
$export = mysqli_query ( $link, $select ) 
   or die ( "Sql error : " . mysql_error( ) );
$fields = mysqli_num_fields ( $export );

//create csv header row, to contain table headers 
//with database field names
for ( $i = 0; $i < $fields; $i++ ) {
$header .= mysqli_fetch_fields( $export ) . ",";
}

//this is where most of the work is done. 
//Loop through the query results, and create 
//a row for each
while( $row = mysqli_fetch_row( $export ) ) {
$line = '';
//for each field in the row
foreach( $row as $value ) {
    //if null, create blank field
    if ( ( !isset( $value ) ) || ( $value == "" ) ){
        $value = ",";
    }
    //else, assign field value to our data
    else {
        $value = str_replace( '"' , '""' , $value );
        $value = '"' . $value . '"' . ",";
    }
    //add this field value to our row
    $line .= $value;
}
//trim whitespace from each row
$data .= trim( $line ) . "\n";
}
//remove all carriage returns from the data
$data = str_replace( "\r" , "" , $data );


//create a file and send to browser for user to download
header("Content-type: application/vnd.ms-excel");
header( "Content-disposition: filename=Infoaanvragen.csv");
print "$header\n$data";
exit;

} 
catch (Exception $e) 
{
    $feedback = $e->getMessage();
}
}

?>

2 个答案:

答案 0 :(得分:1)

http://php.net/manual/en/function.fputcsv.php

您可以为每行传递一个文件句柄和数据,并将其格式化为CSV行,并进行正确的转义。它使用文件,但您可以使用内存文件流来避免命中磁盘

$filename = "php://memory";

$fp = fopen($filename, "w+b");

$rowNum = 1;
while( $row = mysqli_fetch_row( $export ) ) {
    if ($rowNum == 1){
        fputcsv($fp, array_keys($row)); // Headers
    }
    fputcsv($fp, $row) // Data
    $rowNum++;
}
rewind($fp);

var_dump(stream_get_contents($fp));

您可以将行的数组键用于第一个CSV行,并将每行的数组值用于数据。

答案 1 :(得分:1)

使用';'作为分隔符(fputcsv有一个参数,默认情况下它是',')并设置DOS格式的行尾。至少它是phpMyAdmin在用于MS Excel&#34; CSV进行导出时所做的事情。格式。