发新话题
打印

php使用 PEAR Spreadsheet Excel Writer 创建Excel文档

本主题由 cfan 于 2007-11-22 09:29 设置高亮

php使用 PEAR Spreadsheet Excel Writer 创建Excel文档

使用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/
努力为phpres做贡献
时刻准备着,当机会来临时你就成功了
打好基础,增加社会经验
资深技术工程师是我的梦想
承接各种团体网站外包服务和各种it技术培训
准备申请AJAX版大,希望大家支持~~

TOP

发新话题