生活在远方

是的,因为真正的生活是在远方

PHP创建Excel文件

Written By: tr - Nov• 03•08

【本文收录于Go4Pro.org

在我的任氏有无轩页面中,有一个专门记载湖人比赛情况的页面:http://www.rsywx.net/misc/lakers.php。随着NBA 08-09赛季的开幕,这个页面就开始频繁的更新了。

在之前的改版中,我已经将这个页面用Smarty页面重新改写了,这次是要为其加入导出比赛情况到Excel文件的功能。

============

我使用的后台库是PEAR类库中的Spreadsheet_Excel_Writer。安装了PEAR的用户都可以用以下命令安装这个库:

pear install --onlyreqdeps Spreadsheet_Excel_Writer-beta

PEAR还是很方便的。在我的PHP环境中,这个库将安装在<PHP install dir>/PEAR/Spreadsheet下。我习惯将<PHP install dir>/PEAR加入到我的PHP包含路径中去,这样在引用包含文件时可以省力一些。

==========

获取来自数据库的内容等操作就不再赘述,只讲针对Excel导出的部分:

require_once("Spreadsheet/Excel/Writer.php");

$sdate=date("Y-m-d", strtotime($_POST['sYear']."-".$_POST['sMonth']."-".$_POST['sDay']));
$edate=date("Y-m-d", strtotime($_POST['eYear']."-".$_POST['eMonth']."-".$_POST['eDay']));

$rows=getGames($sdate, $edate);
$wb=new Spreadsheet_Excel_Writer();
$wb->send("Laker Games.xls");
$ws=&$wb->addWorksheet("Games_Summary");

$f_title=&$wb->addFormat(array('bold'=>true,
                               'Align'=>'center',
                               'Color'=>'blue',
                               'FgColor'=>'yellow'));

$ws->write(0,0, "Game Sequence", $f_title);
$ws->write(0,1, "Date Played", $f_title);
$ws->write(0,2, "Teams", $f_title);
$ws->write(0,3, "Score", $f_title);
$ws->write(0,4, "Win/Lose", $f_title);
$ws->write(0,5, "Remarks", $f_title);

$rowid=1;
foreach ($rows as $game)
{
    $ws->write($rowid,0, $game['seq']);
    $ws->write($rowid,1, $game['date']);
    $ws->write($rowid,2, $game['team']);
    $ws->write($rowid,3, $game['score']);
    $ws->write($rowid,4, $game['win']);
    $ws->write($rowid,5, iconv('utf-8', 'gb18030', $game['note']));
    $rowid++;
}
$wb->close();

==================
大部分代码是自明的。不做太多的说明,结合PEAR关于Spreadsheet_Excel_Writer的文档,应该很容易知道各行代码的作用。

值得注意的是,以上的代码无法在XAJAX的环境下执行。我猜想,原因在于send函数:

function send($filename)
{
        header("Content-type: application/vnd.ms-excel");
        header("Content-Disposition: attachment; filename=\"$filename\"");
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0,pre-check=0");
        header("Pragma: public");
}

在这个函数中,Writer用header的方式来“欺骗”浏览器,表明将要输出的内容是一个Excel的表格文件。我认为,正是这个HEAD信息破坏了XAJAX(即AJAX)所维系的头信息,造成该函数无法在XAJAX的环境下运行(但是也不出错……)。

Writer并没有提供一个独立的将生成的Excel内容保存起来的函数,有时间、有精力的话在这个方面加以改进应该是不错的。

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

2 Comments

  1. ruanchao says:

    Hi, 您的http://www.rsywx.net/misc/lakers.php这个页面的导出功能有误哦!

  2. tr says:

    @ruanchao

    是的,是有问题,因为我转换服务器后一直没有将导出Excel的库放上去。

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">