• 周六. 7 月 27th, 2024

    PHP导出EXCEL简单实用方法

    root

    10 月 23, 2019 #library, #php常用函数
    /**
         * 得到相应的列表字符串
         *
         * @param $titArr 字段和标题的对应数组
         * @param $data 数据的列表数组
         * @param $fileName 文件的名字
         * @param int $type 类型 1 浏览器生成excel文件  2 直接生成文件
         * @return void 列表table
         */
        public function _showTableListExcel($titArr,$data,$fileName,$type=1)
        {
            $labelStr = $outStr = '';
            if($titArr){
                foreach ($titArr as $val) {
                    $labelStr .= '<td>'.$val.'</td>';
                }
                $labelStr = '<tr>'.$labelStr.'</tr>';
            }
            if($data){
                $showArr = array_keys($titArr);
                foreach ($data as $val) {
                    $rowStr = '';
                    foreach ($showArr as $name) {
                        $rowStr .= '<td>'.$val[$name].'</td>';
                    }
                    $outStr .= '<tr>'.$rowStr.'</tr>';
                }
            }
            $outStr =  '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40">
                       <head>
                       <meta http-equiv=Content-Type content="text/html; charset=gbk">
                       <meta name=ProgId content=Excel.Sheet></head><body><table border="1">'.$labelStr.$outStr.'</table></body></html>';
            //写出方式
            if(1 == $type){
                header("Content-Type:application/vnd.ms-excel");
                header("Content-Disposition:attachment;filename={$fileName}.xls");
                header("Pragma:no-cache");
                header("Expires:0");
                echo $outStr;
            } else {
                Libs_Tools_GlobalFunc::writeFile(array('fileName'=>'/tmp/'.$fileName.'.xls', 'content'=>$outStr));
            }
        }

    该方法可以导出行比较多的excel文档,相比于phpExcel类库好用一些。

    root

    发表回复