使用php将mysql数据导出到excel时,所有字段名都显示在一列中

fnatzsnv  于 2021-06-25  发布在  Mysql
关注(0)|答案(0)|浏览(290)

我已经为下载excel文件编写了一个php脚本,其中包含一些通过mysql查询获取的mysql数据。数据正确,但最上面一行的字段名用逗号显示在一行中。我希望在单个列中有一个字段名。我在代码中遗漏了什么。如果有人知道如何做到这一点,请告诉我。这是我的密码:

<?php
include('connection.php');
$header = '';
$data = '';
$select = "select * from pdbp inner join bp on(pdbp.bp_id=bp.id)";

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

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

//this is where most of the work is done. 
//Loop through the query results, and create 
 //a row for each
while( $row = mysql_fetch_row( $export ) ) {
$line = '';
//for each field in the row
foreach( $row as $value ) {
    //if null, create blank field
    if ( ( !isset( $value ) ) || ( $value == "" ) ){
        $value = "\t";
    }
    //else, assign field value to our data
    else {
        $value = str_replace( '"' , '""' , $value );
        $value = '"' . $value . '"' . "\t";
    }
    //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 );

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

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题