使用
PEAR Spreadsheet_Excel_Writer创建Excel,MS EXCEL不是必需的, OpenOffice Calc也是一个不错的选择。
安装pear:
双击
php目录中的go-pear.bat,一路回车安装完毕。
双击PEAR_ENV.reg写入注册表信息。
在命令窗口输入如下命令安装OLE及Spreadsheet_Excel_Writer
复制内容到剪贴板
代码:
$ pear install [url]http://download.pear.php.net/package/OLE-0.5.tgz[/url]
$ pear install [url]http://download.pear.php.net/package/Spreadsheet_Excel_Writer-0.9.1.tgz[/url]生成一个简单的
电子表格,代码如下:(test.php)
复制内容到剪贴板
代码:
<?php
// Include PEAR::Spreadsheet_Excel_Writer
require_once "Spreadsheet/Excel/Writer.php";
// Create an instance
$xls =& new Spreadsheet_Excel_Writer();
// Send HTTP headers to tell the browser what's coming
$xls->send("test.xls");
// Add a worksheet to the file, returning an object to add data to
$sheet =& $xls->addWorksheet('Binary Count');
// Write some numbers
for ( $i=0;$i<11;$i++ ) {
// Use PHP's decbin() function to convert integer to binary
$sheet->write($i,0,decbin($i));
}
// Finish the spreadsheet, dumping it to the browser
$xls->close();
?>在
浏览器中输入上面test.php文件所在的地址,就可以用excel或者OpenOffice打开一个电子表格。
将生成的excel文档保存到
文件系统。代码如下:
复制内容到剪贴板
代码:
<?php
// 如果文件不存在
if ( !file_exists('sheets/binary.xls') ) {
// Include PEAR::Spreadsheet_Excel_Writer
require_once "Spreadsheet/Excel/Writer.php";
// Create an instance, passing the filename to create
$xls =& new Spreadsheet_Excel_Writer('sheets/binary.xls');
// Add a worksheet to the file, returning an object to add data to
$sheet =& $xls->addWorksheet('Binary Count');
// Write some numbers
for ( $i=0;$i<11;$i++ ) {
// Use PHP's decbin() function to convert integer to binary
$sheet->write($i,0,decbin($i));
}
// Finish the spreadsheet, dumping it to the browser
$xls->close();
}
?>注意,在
linux或Unix下,文件所在目录必须可读。
不是原文照译,参考原文地址如下:
http://www.phphacks.com/content/view/26/33/