2

如何使用 PHP 从 mySQL 表创建 .XLS 文档?

我几乎尝试了所有方法,但没有成功。

基本上,我需要获取表单数据,并将其输入到我已经完成的数据库中,然后我需要检索该表数据并将其解析为 Microsoft excel 文件,该文件需要自动保存到 Web 服务器上。

    <?php

// DB TABLE Exporter
//
// How to use:
//
// Place this file in a safe place, edit the info just below here
// browse to the file, enjoy!

// CHANGE THIS STUFF FOR WHAT YOU NEED TO DO

     $dbhost  = "-";
     $dbuser  = "-";
     $dbpass  = "-";
     $dbname  = "-";
     $dbtable = "-";

// END CHANGING STUFF

$cdate = date("Y-m-d"); // get current date


// first thing that we are going to do is make some functions for writing out
// and excel file. These functions do some hex writing and to be honest I got 
// them from some where else but hey it works so I am not going to question it 
// just reuse


// This one makes the beginning of the xls file
function xlsBOF() {
    echo pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0);
    return;
}

// This one makes the end of the xls file
function xlsEOF() {
    echo pack("ss", 0x0A, 0x00);
    return;
}

// this will write text in the cell you specify
function xlsWriteLabel($Row, $Col, $Value ) {
    $L = strlen($Value);
    echo pack("ssssss", 0x204, 8 + $L, $Row, $Col, 0x0, $L);
    echo $Value;
    return;
}



// make the connection an DB query
$dbc = mysql_connect( $dbhost , $dbuser , $dbpass ) or die( mysql_error() );
mysql_select_db( $dbname );
$q = "SELECT * FROM ".$dbtable." WHERE date ='$cdate'";
$qr = mysql_query( $q ) or die( mysql_error() );

// start the file
xlsBOF();

// these will be used for keeping things in order.
$col = 0;
$row = 0;

// This tells us that we are on the first row
$first = true;

while( $qrow = mysql_fetch_assoc( $qr ) )
{
    // Ok we are on the first row
    // lets make some headers of sorts
    if( $first )
    {
        foreach( $qrow as $k => $v )
        {
            // take the key and make label
            // make it uppper case and replace _ with ' '
            xlsWriteLabel( $row, $col, strtoupper( ereg_replace( "_" , " " , $k ) ) );
            $col++;
        }

        // prepare for the first real data row
        $col = 0;
        $row++;
        $first = false;
    }

    // go through the data
    foreach( $qrow as $k => $v )
    {
        // write it out
        xlsWriteLabel( $row, $col, $v );
        $col++;
    }
    // reset col and goto next row
    $col = 0;
    $row++;
}

xlsEOF();
exit();
?>

我似乎无法弄清楚如何将 fwrite 集成到所有将生成的数据写入 .xls 文件中,我将如何去做呢?

我需要非常紧急地完成这项工作,因此将不胜感激任何帮助。谢谢各位。

4

5 回答 5

1

我在我的项目中经常使用 PEAR Spreadsheet_Excel_Writer并且效果很好。但是,它会生成 Excel 5.0 级别的文件,因此如果您需要比这更高级的任何东西,它可能不足以满足您的目的,但它会生成一个本机 .xls,而不仅仅是伪装成 .xls 的 .csv。

于 2010-03-22T15:08:09.480 回答
1

如果您的数据库有某种前端(如 phpMyAdmin 或 SQLyog),您可以将表(或任何 SELECT 查询的结果)导出到 CSV 并在 Excel 中打开。

评论后编辑:我创建了一个 XLS 一次。这有点不同,但我所做的是把它放在我的 PHP 的顶部(在生成任何输出之前):

header("Content-type: application/vnd.ms-excel");
header("Content-disposition: attachment; filename=\"name.xls\"");

在脚本的其余部分,我只是回显了一个表(表、tr、td...等)。这个脚本的执行会给用户一个下载。我认为 Content-disposition 属性有一些不同的选项(也许有一个可以让脚本保存文件)。

于 2010-03-22T08:58:00.383 回答
0

一切正常,这里是答案所在。:-)

使用 fwrite 保存 .xls 文件

于 2010-03-25T11:22:14.390 回答
0

如果我做对了,您发布的脚本工作正常并创建了一个正确的 xls 文件,而您只想保存输出,请查看http://php.net/manual/en/book.outcontrol.php。使用 ob_get_clean(),您可以获取创建的 xls 文件并将其写入服务器的某个位置。

也许,您还可以考虑其他选项,例如将数据保存为 Excel 可以读取的其他格式(.csv,可能它也可以读取一些 html/xml 表)。

于 2010-03-22T09:07:19.867 回答
0

我用 ob_get_clean() 试过了,但没用,这是我现在一直在处理的代码:

<?php

// DB TABLE Exporter
//
// How to use:
//
// Place this file in a safe place, edit the info just below here
// browse to the file, enjoy!

// CHANGE THIS STUFF FOR WHAT YOU NEED TO DO

     $dbhost  = "-";
     $dbuser  = "-";
     $dbpass  = "-";
     $dbname  = "-";
     $dbtable = "-";

// END CHANGING STUFF

$cdate = date("Y-m-d"); // get current date


// first thing that we are going to do is make some functions for writing out
// and excel file. These functions do some hex writing and to be honest I got 
// them from some where else but hey it works so I am not going to question it 
// just reuse


// This one makes the beginning of the xls file
function xlsBOF() {
    $output = pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0);
    return;
}

// This one makes the end of the xls file
function xlsEOF() {
    $output .= pack("ss", 0x0A, 0x00);
    return;
}

// this will write text in the cell you specify
function xlsWriteLabel($Row, $Col, $Value ) {
    $L = strlen($Value);
    $output .= pack("ssssss", 0x204, 8 + $L, $Row, $Col, 0x0, $L);
    $file = fopen("exported.xls","w");
    fwrite($file, "$output");
    fclose($file);
    return;
}



// make the connection an DB query
$dbc = mysql_connect( $dbhost , $dbuser , $dbpass ) or die( mysql_error() );
mysql_select_db( $dbname );
$q = "SELECT * FROM ".$dbtable." WHERE date ='$cdate'";
$qr = mysql_query( $q ) or die( mysql_error() );


// Ok now we are going to send some headers so that this 
// thing that we are going make comes out of browser
// as an xls file.
// 
//header("Pragma: public");
//header("Expires: 0");
//header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
//header("Content-Type: application/force-download");
//header("Content-Type: application/octet-stream");
//header("Content-Type: application/download");

//this line is important its makes the file name
//header("Content-Disposition: attachment;filename=export_".$dbtable.".xls ");

//header("Content-Transfer-Encoding: binary ");

// start the file
xlsBOF();

// these will be used for keeping things in order.
$col = 0;
$row = 0;

// This tells us that we are on the first row
$first = true;

while( $qrow = mysql_fetch_assoc( $qr ) )
{
    // Ok we are on the first row
    // lets make some headers of sorts
    if( $first )
    {
        foreach( $qrow as $k => $v )
        {
            // take the key and make label
            // make it uppper case and replace _ with ' '
            xlsWriteLabel( $row, $col, strtoupper( ereg_replace( "_" , " " , $k ) ) );
            $col++;
        }

        // prepare for the first real data row
        $col = 0;
        $row++;
        $first = false;
    }

    // go through the data
    foreach( $qrow as $k => $v )
    {
        // write it out
        xlsWriteLabel( $row, $col, $v );
        $col++;
    }

    // reset col and goto next row
    $col = 0;
    $row++;

}

xlsEOF();
exit();



?>

我什至不知道这是否有意义,但我在 xlsBOF、xlsEOF 和 xlsWriteLabel 函数中添加了 fwrite 以尝试将数据写入exported.xls 文件,它可以这样工作吗?

于 2010-03-22T12:40:01.027 回答