PHP导出Excel 之 Spreadsheet_Excel_Writer
时间:2011-04-06 来源:niefeng0814
一、安装、注册PEAR(Windows下)
- 运行php目录下的go-pear.bat;
- 按提示进行相应的操作即可完成;
- 注册,点击php下的PEAR_ENV.reg进行注册
- 修改php.ini: include_path = “.;G:\PHP5\PEAR”(Windows修改这行),之后重新启动apache;
二、安装Spreadsheet_Excel_Writer包(Windows下):
- Spreadsheet_Excel_Writer-0.9.1包,必须先安装OLE-0.5包;
- cmd –》命令窗口;
- 到php的安装目录:如G:\PHP5;
- 进行安装,注:命令前为“pear.bat ”,如:G:\PHP5>pear.bat install Spreadsheet_Excel_Writer-0.9.1,这样就安装成功了。
三、Spreadsheet_Excel_Writer应用:
<?php
//包含pear的类
require_once “Spreadsheet/Excel/Writer.php”;
// 创建一个实例
$xls = &new Spreadsheet_Excel_Writer();
//设置版本号
$xls->setVersion(8);
// Send HTTP headers to tell the browser what’s coming
$title = iconv(‘utf-8′, ‘gbk’, ‘用户列表’);
$xls->send($title.”.xls”);
// Add a worksheet to the file, returning an object to add data to
$sheet = &$xls->addWorksheet(‘User List’);
$sheet->setInputEncoding(‘utf-8′); //设置编码格式
$format = &$xls->addFormat(); //设置excel中的样式
$format->setAlign(‘center’); //居中样式
$sheet->setColumn(0, 9, 20); //设置列宽
$sheet->setMerge(0, 0, 0, 3); //合并行和列(开始行,开始列,结束行,结束列)
$sheet->write(0, 0, ‘User List’, $format);
//横向的所有的标题
$sheet->write(1, 0, ‘姓名’, $format);
$sheet->write(1, 1, ‘年龄’, $format);
$sheet->write(1, 2, ‘性别’, $format);
$sheet->write(1, 3, ‘婚否’, $format);
$sheet->write(2, 0, ‘涛哥’, $format);
$sheet->write(2, 1, 88, $format);
$sheet->write(2, 2, ‘男’, $format);
$sheet->write(2, 3, ‘已婚’, $format);
$sheet->write(3, 0, ‘春哥’, $format);
$sheet->write(3, 1, 25, $format);
$sheet->write(3, 2, ‘男’, $format);
$sheet->write(3, 3, ‘未婚’, $format);
// Finish the spreadsheet, dumping it to the browser
$xls->close();