PHP生成Excel
PHP生成Excel 首先想到的是使用Pear的Spreadsheet_Excel_Writer
网址:http://pear.php.net/package/Spreadsheet_Excel_Writer
如果台湾人使用,那么要修改如:开始-所有程序-Microsoft Office-Microsoft Office工具-Microsoft Office 2007语言设置-下边的主要编辑语言选中”中文(中国)” ,因为繁体问题研究了3天.使用了多种方法,最终这样解决$_%.
一个字:真累!
/**
* PHP使用Pear的Spreadsheet_Excel_Writer生成excel文件
* 可以同时使用繁体字和简体字
* 下边有使用方法,如果是测试可能要在另一页做个到这页的链接,因为是直接下载(输出)excel文件
* @author http://www.zhaipeng.cn/
* @time 2008-11-21
* @example
$columns = array(
'id'=>'ID',
'title'=>'名称',
'url'=>'网址'
);
//一般查询数据库后的数据,例如adodb的getArray,getAll
$rows = array(
array('id'=>1 , 'title'=>'翟鹏的博客' , 'url'=>'http://www.zhaipeng.cn/'),
array('id'=>3 , 'title'=>'MySQL Wiki' , 'url'=>'http://www.mysql6.org/' ,'other'=>'没用不在columns'),
);
$e = new MyExcel('演示excel');
$e->worksheet('第一个工作表' , $columns , $rows);
//再加一个,不写那么多代码了,还是用上边的数据
$e->worksheet('第二个工作表' , $columns , $rows);
$e->close();
*/
//error_reporting(E_ALL);
//set_time_limit(120);
//ini_set('memory_limit','64M');
//ini_set('include_path', dirname(__FILE__) . DIRECTORY_SEPARATOR .'PEAR'.
PATH_SEPARATOR.ini_get('include_path'));
include_once( 'Spreadsheet/Excel/Writer.php' ) ;
class MyExcel{
var $workbook ;
var $from_encoding ;
var $to_encoding ;
/**
* 为了在PHP4下使用,没有使用__construct
*
* @param string $name 生成的excel文件名称
* @param string $from_encoding 如果和我一样就是utf-8
* @param string $to_encoding 生成的excel编码,中文一般用gb2312,为了使用繁体字推荐gbk
* @return MyExcel
*/
function MyExcel($name = 'name' , $from_encoding = 'utf-8' , $to_encoding = 'gbk'){
$this->workbook = new Spreadsheet_Excel_Writer(); // 初始化类
$this->from_encoding = $from_encoding;
$this->to_encoding = $to_encoding;
$this->workbook->send( $this->replaceEncode($name).'.xls');
}
/**
* 加入工作表
*
* @param string $name 工作表名称
* @param array $columns 列名
* @param array $rows 数据
*/
function worksheet($name , $columns , $rows){
// 加入一个工作表
$worksheet =& $this->workbook->addWorksheet($this->replaceEncode($name));
//设定编码
$worksheet->setInputEncoding($this->to_encoding);
$i = 0 ;
foreach($columns AS $title){
$worksheet->write( 0 , $i ++ , $this->replaceEncode($title));
}
$i = 0 ;
foreach($rows AS $row) :
if( ++$i >= 65536) break;
$j = 0;
foreach($columns AS $k=>$v){
if (!isset($row[$k]) || is_null($row[$k])) {
$worksheet->write($i, $j, ''); //null
}elseif($row[$k] == ''){
$worksheet->write($i, $j, '');
}else{
$worksheet->write($i, $j, $this->replaceEncode($row[$k]));
}
$j ++;
}
endforeach;
}
/**
* 结束并输出
*
*/
function close(){
$this->workbook->close();
}
/**
* 如果输入与输出编码不同要转换文字编码
*
* @param string $str 文字内容
* @return 转换后的文字内容
*/
function replaceEncode($str){
if(strtolower($this->to_encoding) == strtolower($this->from_encoding)){
return $str;
}
//如果没有mb_string当然可以使用其它转换方法,如iconv或码表 但有个别字不能转换!
$str = mb_convert_encoding($str , $this->to_encoding , $this->from_encoding);
return $str;
}
}


