很多人用PHP来导出数据到Excel,都是采用phpexcel这个老外写的程序,这个程序很强大,但是实在是太庞大了,解压都17MB了,实在是太臃肿了。火端网络最近需要用PHP导出数据到Excel文件,在网上找的一个类,很简单,测试成功,虽然导出xsl文件后,打开提示“格式不对,是否要打开”,但选择“是”后还是可以正常显示导出的数据的。
下面就是类代码,使用也很简单:
/**
* 生成excel文件操作
*
* @author wesley wu
* @date 2013.12.9
*/
class Excel
{
private $limit = 10000;
public function download($data, $fileName)
{
$fileName = $this->_charset($fileName);
header("Content-Type: application/vnd.ms-excel; charset=gbk");
header("Content-Disposition: inline; filename=\"" . $fileName . ".xls\"");
echo "<?xml version=\"1.0\" encoding=\"gbk\"?>\n
xmlns:x=\"urn:schemas-microsoft-com:office:excel\"
xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\"
xmlns:html=\"http://www.w3.org/TR/REC-html40\">";
echo "\n\n
$guard = 0;
foreach($data as $v)
{
$guard++;
if($guard==$this->limit)
{
ob_flush();
flush();
$guard = 0;
}
echo $this->_addRow($this->_charset($v));
}
echo "
\n\n";}
private function _addRow($row)
{
$cells = "";
foreach ($row as $k => $v)
{
$cells .= "" . $v . "\n";
}
return "\n" . $cells . "\n";
}
private function _charset($data)
{
if(!$data)
{
return false;
}
if(is_array($data))
{
foreach($data as $k=>$v)
{
$data[$k] = $this->_charset($v);
}
return $data;
}
return iconv('utf-8', 'gbk', $data);
}
}
//使用方法
$excel = new Excel();
$data = array(
array('姓名','标题','网址','价格','数据5','数据6','数据7'),
array('火端网络','数据2','https://www.huoduan.com','数据4','数据5','数据6','数据7'),
array('数据1','数据2','数据3','数据4','数据5','数据6','数据7'),
array('数据1','数据2','数据3','数据4','数据5','数据6','数据7'),
array('数据1','数据2','数据3','数据4','数据5','数据6','数据7'),
array('数据1','数据2','数据3','数据4','数据5','数据6','数据7')
);
$excel->download($data, '这是一个测试');
?>