从Mysql表导出Excel

时间:2014-11-10 15:38:33

标签: php mysqli

请让别人帮我解决这个问题,当我导出时,它导出文件但是从row2开始,第一行被排除。读取像,标题,然后是row2,3,4直到行结束

<?php
        require_once("/includes/session.php");
         require_once("/includes/db_connection.php");
         require_once("/includes/functions.php");
        // Table Name that you want
        // to export in csv
        $ShowTable = "staff_tab";
         $today=date("dmY");
        $FileName = "StaffRecord".$today.". csv";
        $file = fopen($FileName,"w");

        $sql = mysqli_query($connection,("SELECT * FROM $ShowTable LIMIT 500"));
        $row = mysqli_fetch_assoc($sql);
        // Save headings alon
        $HeadingsArray=array();
        foreach($row as $name => $value){
        $HeadingsArray[]=$name;
        }
        fputcsv($file,$HeadingsArray);
        // Save all records without headings

        while($row = mysqli_fetch_assoc($sql)){
        $valuesArray=array();
        foreach($row as $name => $value){
        $valuesArray[]=$value;
        }
        fputcsv($file,$valuesArray);
        }
        fclose($file);

        header("Location: $FileName");

        echo "Complete Record saves as CSV in file: <b style=\"color:red;\">$FileName</b>";
        ?>

2 个答案:

答案 0 :(得分:0)

您对$row = mysqli_fetch_assoc($sql);的调用是将内部指针向前推到第2行。使用mysqli_data_seek($sql, 0);将其推回到开头。 http://php.net/manual/en/function.mysql-data-seek.php

    ...
    $sql = mysqli_query($connection,("SELECT * FROM $ShowTable LIMIT 500"));
    $row = mysqli_fetch_assoc($sql);
    mysqli_data_seek($sql, 0);           // return pointer to first row
    // Save headings alon
    $HeadingsArray=array();
    ...

答案 1 :(得分:0)

这可能会有所帮助,因为这将包括db头中的所有行和set头。这也会强制下载文件而不会离开页面。

$export = mysqli_query ($query) or die ( "Sql error : " . mysqli_error( ) );

// extract the field names for header
$fields = mysqli_num_fields ( $export );

for ( $i = 0; $i < $fields; $i++ )
{

    $headers = mysqli_fetch_field($export);
    $header .= $headers->name. "\t";
}

// export data
while( $row = mysqli_fetch_row( $export ) )
{
    $line = '';
    foreach( $row as $value )
    {
        if ( ( !isset( $value ) ) || ( $value == "" ) )
        {
            $value = "\t";
        }
        else
        {
            $value = str_replace( '"' , '""' , $value );
            $value = '"' . $value . '"' . "\t";
        }
        $line .= $value;
    }
    $data .= trim( $line ) . "\n";
}
$data = str_replace( "\r" , "" , $data );

if ( $data == "" )
{
    $data = "\nNo Record(s) Found!\n";
}

// allow exported file to download forcefully
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=Something.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";