使用PHP生成MySQL到Excel

pmm*_*mms 2 php mysql excel xls

<?php
    // DB Connection here
    mysql_connect("localhost","root","");
    mysql_select_db("hitnrunf_db");

    $select = "SELECT * FROM jos_users ";
    $export = mysql_query ( $select ) or die ( "Sql error : " . mysql_error( ) );
    $fields = mysql_num_fields ( $export );

    for ( $i = 0; $i < $fields; $i++ )
    {
        $header .= mysql_field_name( $export , $i ) . "\t";
    }

    while( $row = mysql_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 = "\n(0) Records Found!\n";
    }

    header("Content-type: application/octet-stream");
    header("Content-Disposition: attachment; filename=your_desired_name.xls");
    header("Pragma: no-cache");
    header("Expires: 0");
    print "$header\n$data";
?>
Run Code Online (Sandbox Code Playgroud)

上面的代码用于从MySQL数据库生成Excel电子表格,但我们收到以下错误:

您尝试打开的文件"users.xls"的格式与文件扩展名指定的格式不同.在打开文件之前,请验证文件是否已损坏且是否来自受信任的源.你想现在打开文件吗?

有什么问题,我们如何解决?

Mar*_*c B 5

你真的不是在生成Excel文件.您使用制表符作为分隔符生成相当于.csv文件的内容.

要生成"真正的"Excel文件,请使用PHPExcel.