【发布时间】:2015-08-05 17:56:00
【问题描述】:
我需要从 Mysql 表“tblinfoaanvraag”中导出数据(表的图片见这里:http://s29.postimg.org/qeqp43z4n/mysql.png)
我有一个带有正确查询的工作代码,它会触发 Excel 下载并且数据在文件中。但是,Excel 文件中的数据仍然被格式化为 sql 查询结果,并且表头(字段名)仅显示为“数组”。
因此,此时我正在努力解决两件事:将 sql-results 格式化为 .csv 文件中的单元格,并且应正确显示标题/表字段名称,而不仅仅是“数组”。
这是下载的 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();
}
}
?>
【问题讨论】: