其实导出excel格式最简单的用csv,php本身就有fputcsv这个很帅的函数将一个数组直接写成csv文件。但是如果想要在一个文件中建立多个工作簿用csv就不靠谱了。PHP输出Excel的现成类蛮多的,有基于pear、历史悠久的Spreadsheet_Excel_Writer,基于xml的新锐PHPExcel,他们功能都很好很强大,可以设置单元格格式什么的。但是如果我们仅仅是为了输出简单的二维的数据表格,没有必要用到这么大的家伙。一个是安装麻烦,PHPExcel还需要php5.2以上才行,另外一个大问题就是输出数据很大的时候内存可能会溢出。下面给出的类将采用Excel最简单的格式要求,边输出数据边写的方式来减少对内存的占用。最简单的excel格式请看这里:
下面是整个类的代码:
class ExcelWriter{ var $fp=null; var $error; var $state="CLOSED"; var $newRow=false; var $header; function ExcelWriter($file=""){ if($this->state != "CLOSED"){ $this->error = "Error : Another file is opend .Close it to save the file"; return false; } if(!empty($file)){ if(file_exists($file)) unlink($file); $this->fp = @fopen($file,"w+"); }else{ $this->error = "Usage : New ExcelWriter('fileName')"; return false; } if($this->fp == false){ $this->error = "Error: Unable to open/create File.You may not have permmsion to write the file."; return false; } $this->state = "OPENED"; $this->makeHeader(); return true; } function close(){ if($this->state != "OPENED"){ $this->error="Error : Please open the file."; return false; } $this->makeFooter();
fclose($this->fp); $this->state="CLOSED"; return true; }
function makeHeader(){ $str = "
";
$str .= <<<EOH <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns:html="">
EOH; fwrite($this->fp, $str);
return true; }
function addSheet($name){ $str = "
";
fwrite($this->fp, $str);
return true; } function addRow($aData){ if($this->state!="OPENED"){ $this->error="Error : Please open the file."; return false; } if(!is_array($aData)){ $this->error="Error : Argument is not valid. Supply an valid Array."; return false; } $rowstr = " " ; foreach($aData as $col){ $rowstr .= " $col | "; } $rowstr .= " "; fwrite($this->fp,$rowstr);
return true; }
function endSheet(){ $str = <<<EOH </Table> </Worksheet>
EOH; fwrite($this->fp, $str);
return true; } function makeFooter(){ $str = "
"; fwrite($this->fp, $str);
return true; } };
阅读(1527) | 评论(0) | 转发(0) |
|