简体   繁体   English

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

[英]Export Mysql table data to Excel through PHP: Data not showing properly in Excel

I need to export the data from the Mysql table “tblinfoaanvraag” (see here for picture of the table: http://s29.postimg.org/qeqp43z4n/mysql.png ) 我需要从Mysql表“ tblinfoaanvraag”中导出数据(有关表的图片,请参见此处: http ://s29.postimg.org/qeqp43z4n/mysql.png)

I have a working code with the correct query and it triggers an Excel download and the data is in the file. 我有一个带有正确查询的工作代码,它会触发Excel下载,并且数据在文件中。 However, The data inside the Excel file is still formatted as an sql query result and the headers (field names) are only shown as “Array”. 但是,Excel文件中的数据仍被格式化为sql查询结果,并且标头(字段名称)仅显示为“ Array”。

So there are two things I'm struggling with at this point: format the sql-results as cells in the .csv file and the headers/table field names should be shown correctly instead of just “Array”. 因此,此时我要努力解决两件事:将sql结果格式设置为.csv文件中的单元格,并且标头/表字段名称应正确显示,而不仅仅是“ Array”。

Here is a screenshot of the downloaded Excel-file: http://s13.postimg.org/p0rcehehj/excel1.png 这是下载的Excel文件的屏幕截图: http : //s13.postimg.org/p0rcehehj/excel1.png

The code: 编码:

<?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();
}
}

?>

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

You can pass it a file handle and your data for each row, and it formats it as a CSV line, with correct escapings. 您可以向其传递文件句柄和每一行的数据,并将其格式化为CSV行,并带有正确的转义符。 It uses a file, though you can use an in memory file stream to avoid hitting the disk 它使用一个文件,尽管您可以使用内存中的文件流来避免碰到磁盘

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

You would use the array keys of a row for first CSV row, and array values of each row for data. 您应将一行的数组键用于第一个CSV行,并将每行的数组值用于数据。

Use ';' 使用';' as delimiter ( fputcsv has a parameter for that and it's ',' by default) and set the end of lines in DOS format. 作为分隔符( fputcsv有一个参数,默认情况下为',' ),并以DOS格式设置行尾。 At least it's what phpMyAdmin does when doing an export in the "CSV for MS Excel" format. 至少这是以“ My Excel CSV”格式导出时phpMyAdmin所做的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM