• PHP生成excel表格文件并下载


    [php] view plain copy
     
    1. function createtable($list,$filename){    
    2.     header("Content-type:application/vnd.ms-excel");    
    3.     header("Content-Disposition:filename=".$filename.".xls");    
    4.     
    5.     $strexport="编号 姓名 性别 年龄 ";    
    6.     foreach ($list as $row){    
    7.       
    8.         $strexport.=$row['id']." ";     
    9.         $strexport.=$row['username']." ";    
    10.         $strexport.=$row['sex']." ";    
    11.         $strexport.=$row['age']." ";    
    12.           
    13.     }    
    14.     $strexport=iconv('UTF-8',"GB2312//IGNORE",$strexport);    
    15.     exit($strexport);       
    16. }  

    基于这个我们可以将方法封装一下:
    [php] view plain copy
     
    1. /** 
    2.  * 创建(导出)Excel数据表格 
    3.  * @param  array   $list 要导出的数组格式的数据 
    4.  * @param  string  $filename 导出的Excel表格数据表的文件名 
    5.  * @param  array   $header Excel表格的表头 
    6.  * @param  array   $index $list数组中与Excel表格表头$header中每个项目对应的字段的名字(key值) 
    7.  * 比如: $header = array('编号','姓名','性别','年龄'); 
    8.  *       $index = array('id','username','sex','age'); 
    9.  *       $list = array(array('id'=>1,'username'=>'YQJ','sex'=>'男','age'=>24)); 
    10.  * @return [array] [数组] 
    11.  */  
    12. protected function createtable($list,$filename,$header=array(),$index = array()){    
    13.     header("Content-type:application/vnd.ms-excel");    
    14.     header("Content-Disposition:filename=".$filename.".xls");    
    15.     $teble_header = implode(" ",$header);  
    16.     $strexport = $teble_header." ";  
    17.     foreach ($list as $row){    
    18.         foreach($index as $val){  
    19.             $strexport.=$row[$val]." ";     
    20.         }  
    21.         $strexport.=" ";   
    22.   
    23.     }    
    24.     $strexport=iconv('UTF-8',"GB2312//IGNORE",$strexport);    
    25.     exit($strexport);       
    26. }   
    方法调用:
    [php] view plain copy
     
    1. $filename = '提现记录'.date('YmdHis');  
    2. $header = array('会员','编号','联系电话','开户名','开户行','申请金额','手续费','实际金额','申请时间');  
    3. $index = array('username','vipnum','mobile','checkname','bank','money','handling_charge','real_money','applytime');  
    4. $this->createtable($cash,$filename,$header,$index);  
    运行就可以得到表格:


    这种方式生成Excel文件,生成速度很快,但是有缺点是:
    1.单纯的生成Excel文件,生成的文件没有样式,单元格属性(填充色,宽度,高度,边框颜色...)不能自定义;
    2.生成的文件虽然可以打开,但是兼容性很差,每次打开,都会报一个警告:

    解决这个问题也不难,具体参见:使用PHPExcel实现Excel文件的导入和导出

  • 相关阅读:
    python(十二)面向对象编程、类
    如何搭建测试环境
    python(十一)接口开发、写日志、发邮件、python来发请求、手动添加环境变量
    python(十):模块相关、操作Redis、操作Excel
    Python(九):递归+内置函数+第三方模块+md5加密+操作mysql
    Python(八) 函数、模块
    python练习题
    Python(七) 元组+集合+随机+string
    Python(六)操作文件+非空即真
    VUE基础-1
  • 原文地址:https://www.cnblogs.com/yszr/p/8377770.html
Copyright © 2020-2023  润新知