Home >Backend Development >PHP Tutorial >How to create or export Excel data table with PHP
This article mainly shares with you how to create or export Excel data tables with PHP. It mainly shares with you a piece of code. I hope it can help you.
$filename = "order_".date('Y-m-d').".xls"; $header = array('订单编号','订单类型','会员ID','总加工费','商品总价','邮费','应付金额','订单状态','下单时间'); $index = array('order_sn','kind','mid','other_price','goods_price','shipping_price','order_amount','order_status','regtime'); $$orderlist = M('table')->where($where)->order('id')->select(); create_xls($orderlist,$filename,$header,$index); /** * 数组转xls格式的excel文件 * @param array $data 要导出的数组格式的数据 * @param string $filename 导出的Excel表格数据表的文件名 * @param array $header Excel表格的表头 * @param array $index $list数组中与Excel表格表头$header中每个项目对应的字段的名字(key值) * 比如: $header = array('编号','姓名','性别','年龄'); * $index = array('id','username','sex','age'); * $data = array(array('id'=>1,'username'=>'YQJ','sex'=>'男','age'=>24)); * 示例数据: $strexport = array( array(NULL, 2010, 2011, 2012), array('Q1', 12, 15, 21), array('Q2', 56, 73, 86), array('Q3', 52, 61, 69), array('Q4', 30, 32, 0), ); */ function create_xls($data,$filename='simple.xls',$header,$indexKey){ ini_set('max_execution_time', '0'); Vendor('PHPExcel.PHPExcel'); $filename=str_replace('.xls', '', $filename).'.xls'; $phpexcel = new PHPExcel(); $phpexcel->getProperties() ->setCreator("Maarten Balliauw") ->setLastModifiedBy("Maarten Balliauw") ->setTitle("Office 2007 XLSX Test Document") ->setSubject("Office 2007 XLSX Test Document") ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.") ->setKeywords("office 2007 openxml php") ->setCategory("Test result file"); //组合单元格的内容 foreach ($data as $k=>$row) { foreach ($indexKey as $key=>$value){ //这里是设置单元格的内容 $strexport[$k][$key]=$row[$value]; } } array_unshift($strexport,$header); $phpexcel->getActiveSheet()->fromArray($strexport); $phpexcel->getActiveSheet()->setTitle('Sheet1'); $phpexcel->setActiveSheetIndex(0); header('Content-Type: application/vnd.ms-excel'); header("Content-Disposition: attachment;filename=$filename"); header('Cache-Control: max-age=0'); header('Cache-Control: max-age=1'); header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1 header ('Pragma: public'); // HTTP/1.0 $objwriter = PHPExcel_IOFactory::createWriter($phpexcel, 'Excel5'); $objwriter->save('php://output'); exit; }
Related recommendations:
The above is the detailed content of How to create or export Excel data table with PHP. For more information, please follow other related articles on the PHP Chinese website!