Original article from (www.ympfb.com/show-30-61-… PHP development export Excel table, how to write code? Today, I want to share this with you. What we want to do is to export the data from the database, export it into Excel, export it into what we want according to our rules, and then directly give you the source code.
How does PHP export data into Excel tables?
This is the concrete logical code
$list = Db::table('form')->where('create_time', '>', $stat_time)->select() ->where('create_time','<',$end_time); If (empty($list)){echo "<script>alert(' no data '); window.history.back(); </script>"; exit(); } //dump($list); die; foreach ($list as $key => $value) { $tuij=Db::table('form')->where('id',$value['id'])->find(); $arr[$key]['username']=$tuij['username']; $arr[$key]['phone']=$tuij['phone']; $arr[$key]['source']=$tuij['source']; $arr[$key]['text']=$value['text']; $arr[$key]['create_time']=$value['create_time']; } if(empty($list)){echo "<script>alert(' no data '); window.history.back(); </script>"; exit(); } / / $list for the exported data required for $header = array (' name ', 'phone', 'source', 'messages',' submit time '); $index=array('username','phone','source','text','create_time'); $filename=" form landing page valid promotion "; $this->createtable($arr,$filename,$header,$index); }Copy the code
The last line of the above code refers to the createTable method, which is a public method. You can place it in a public class or directly in this class
Function createTable ($list,$filename,$header,$index){function createTable ($list,$filename,$header,$index){ header("Content-type:application/vnd.ms-excel"); header("Content-Disposition:filename=".$filename.".xls"); $teble_header = implode("\t",$header); $strexport = $teble_header."\r"; foreach ($list as $row){ foreach($index as $val){ $strexport.=$row[$val]."\t"; } $strexport.="\r"; } $strexport=iconv('UTF-8',"GB2312//IGNORE",$strexport); exit($strexport); }Copy the code