经常是mysql查出二维数组,并且数组的带key也是有意义的,考虑到经常用,就打算弄个函数出来,方便以后用!
相对是规范的数组哈,具体可看下$data数组;
生成的excel第一行是对应的key;
直接上代码:
<?php /** * User: Klaus * Date: 2016/5/16 17:04 */ date_default_timezone_set('PRC'); header("Content-type: text/html; charset=utf-8"); include "E:/klaus/work/PHPdiscuz/plugin/phpexcel/PHPExcel.php";//引入phpexcel $data[] = array('uid' => 1, 'email' => 'asda@qq.com', 'password' => 'asdsadasd', 'password1' => 'asdsadasd', 'password2' => 'asdsadasd'); $data[] = array('uid' => 1, 'email' => 'asda@qq.com', 'password' => 'asdsadasd', 'password1' => 'asdsadasd', 'password2' => 'asdsadasd'); $data[] = array('uid' => 1, 'email' => 'asda@qq.com', 'password' => 'asdsadasd', 'password1' => 'asdsadasd', 'password2' => 'asdsadasd'); $data[] = array('uid' => 1, 'email' => 'asda@qq.com', 'password' => 'asdsadasd', 'password1' => 'asdsadasd', 'password2' => 'asdsadasd'); $data[] = array('uid' => 1, 'email' => 'asda@qq.com', 'password' => 'asdsadasd', 'password1' => 'asdsadasd', 'password2' => 'asdsadasd'); $data[] = array('uid' => 1, 'email' => 'asda@qq.com', 'password' => 'asdsadasd', 'password1' => 'asdsadasd', 'password2' => 'asdsadasd'); $data[] = array('uid' => 1, 'email' => 'asda@qq.com', 'password' => 'asdsadasd', 'password1' => 'asdsadasd', 'password2' => 'asdsadasd'); arrToExcel($data,'lptest'); function arrToExcel($data,$name) { //处理数据,获取key $keys = array_keys($data[0]); $objPHPExcel = new PHPExcel(); // 修改sheet名称 $objPHPExcel->getActiveSheet()->setTitle($name . '_' . date('Ymd_His')); // 读取数组 for ($j = 1; $j <= count($data); $j++) { for ($k = 1; $k <= count($data[0]); $k++) { $colname = PHPExcel_Cell::stringFromColumnIndex($k - 1); // 从o开始 $colname .= $j; if ($j == 1) { $value = $keys[$k - 1]; } else { $key = $keys[$k - 1]; $value = $data[$j - 1][$key]; } $objPHPExcel->setActiveSheetIndex(0) ->setCellValue($colname, $value); } } //设置列宽 $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(49); // Set active sheet index to the first sheet, so Excel opens this as the first sheet $objPHPExcel->setActiveSheetIndex(0); // Redirect output to a client’s web browser (Excel5) header('Content-Type: application/vnd.ms-excel'); header('Content-Disposition: attachment;filename=' . $name . '_' . date('Ymd_His') . '.xls'); header('Cache-Control: max-age=0'); $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); $objWriter->save('php://output'); }
结果如图:
列数变下,行数变下:
结过如图:
对了补充下,sheet的名字也是变得哦!
第一次:
第二次:
大功告成!