gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 12:32:39 24 4
gpt4 key购买 nike

我编写了一个简单的 PHP 脚本,用于下载 Excel 文件,其中包含通过 MySQL 查询获取的一些 MySQL 数据。数据正确,但当我在 Excel 文件中打印结果时,所有字段都出现在 Excel 文件的第一列中,这是不正确的。我想要单列中的单个字段。我在代码中缺少什么。如果有人知道如何实现这一目标,请。这是我的代码 -

include('db_connect.php');
$select = "select `dp_id`,`client_id`,`invester_name`,`pan_no` from
(SELECT `dp_id` , `client_id` , `invester_name` , `pan_no`
FROM `app_form` union all
SELECT `dp_id`,`client_id`,`first_holder_name`,`first_holder_pan` FROM `response_record`)
tbl order by `dp_id`,`client_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 = ",";
}
//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 );

$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;

这是我运行此脚本后得到的 Excel 文件的屏幕截图 - enter image description here

最佳答案

替换代码的以下部分:

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;
}

与:

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;
}

并检查它是否适合我

关于php - 使用php将mysql数据导出到excel时,所有字段都显示在一列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27249330/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com