项目中需要将表中的数据导出,在网上找了找发现phpexcel蛮好用的.特此分享
PHPEXCEL
<?php if(!defined('BASEPATH')) exit('No direct script access allowed'); //物资发料单明细 class Read_write{ /** * $name:选择的类型(CSV,EXCEL2003,2007) * $titles:标题数组 * $querys:查询返回的数组 $query->result_array(); * $filename:保存的文件名称 */ function write_Factory($titles,$querys,$filename,$name="EXCEL2003"){ $CI = &get_instance(); $filename=mb_convert_encoding($filename, "GBK","UTF-8"); switch ($name) { case "CSV": $CI->excel->write_CSV($titles,$querys,$filename); break; case "EXCEL2003": $CI->excel->write_EXCEL2003($titles,$querys,$filename); break; case "EXCEL2007": $CI->excel->write_EXCEL2007($titles,$querys,$filename); break; } } /** * $name: */ function read_Facotry($filePath,$sql,$sheet=0,$curRow=2,$riqi=TRUE,$merge=FALSE,$mergeCol="B"){ $CI = &get_instance(); $name=$this->_file_extend($filePath); switch ($name) { case "csv": $CI->excel->read_CSV($filePath,$sql,$sheet,$curRow,$riqi,$merge,$mergeCol); break; case "xls": $CI->excel->read_2003Excel($filePath,$sql,$sheet,$curRow,$riqi,$merge,$mergeCol); break; case "xlsx": $CI->excel->read_EXCEL2007($filePath,$sql,$sheet,$curRow,$riqi,$merge,$mergeCol); break; } $CI->mytool->import_info("filePath=$filePath,sql=$sql"); } /** * 2012-1-14 读取工作薄名称(sheetnames) */ function read_sheetNames($filePath){ $CI = &get_instance(); $name=$this->_file_extend($filePath); $sheetnames; switch ($name) { case "csv": $sheetnames=$CI->excel->read_CSV_Sheet($filePath); break; case "xls": $sheetnames=$CI->excel->read_2003Excel_Sheet($filePath); break; case "xlsx": $sheetnames=$CI->excel->read_EXCEL2007_Sheets($filePath); break; } return $sheetnames; } //读取文件后缀名 function _file_extend($file_name){ $extend =explode("." , $file_name); $last=count($extend)-1; return $extend[$last]; } //-----------------------------------------------预备保留 //2011-12-21新增CVS导出功能 public function export_csv($filename,$title,$datas, $delim = ",", $newline = "\n", $enclosure = '"'){ $CI = &get_instance(); $cvs= $this->_csv_from_result($title,$datas,$delim,$newline,$enclosure); $CI->load->helper('download'); $name=mb_convert_encoding($filename, "GBK","UTF-8"); force_download($name, $cvs); } /** * @param $titles:标题 * @param $datas:数据 */ function _csv_from_result($titles,$datas, $delim = ",", $newline = "\n", $enclosure = '"'){ $out = ''; // First generate the headings from the table column names foreach ($titles as $name){ $name=mb_convert_encoding($name, "GBK","UTF-8"); $out .= $enclosure.str_replace($enclosure, $enclosure.$enclosure, $name).$enclosure.$delim; } $out = rtrim($out); $out .= $newline; // Next blast through the result array and build out the rows foreach ($datas as $row) { foreach ($row as $item) { $item=mb_convert_encoding($item, "GBK","UTF-8"); $out .= $enclosure.str_replace($enclosure, $enclosure.$enclosure, $item).$enclosure.$delim; } $out = rtrim($out); $out .= $newline; } return $out;