摘要:
从官网下载phpexcel文件包。下载地址:http://phpexcel.codeplex.com/releases/view/119187从数据库导出数据到excel文件代码:...
从官网下载phpexcel文件包。
下载地址:http://phpexcel.codeplex.com/releases/view/119187
从数据库导出数据到excel文件代码:
php<?php include '../PHPExcel/PHPExcel.php'; //引入核心库文件 include '../PHPExcel/PHPExcel/Writer/Excel2007.php'; //引入excel2007操作类 include '../PHPExcel/PHPExcel/IOFactory.php'; $objPHPExcel = new PHPExcel(); //实例化phpexcel对象 //创建人 $objPHPExcel->getProperties()->setCreator("{$_SESSION['adminName']}"); //最后修改人 $objPHPExcel->getProperties()->setLastModifiedBy("{$_SESSION['adminName']}"); //标题 $objPHPExcel->getProperties()->setTitle("Office 2007 XLSX all user list Document"); //题目 $objPHPExcel->getProperties()->setSubject("Office 2007 XLSX all user list Document"); //描述 $objPHPExcel->getProperties()->setDescription("all user list"); //关键字 $objPHPExcel->getProperties()->setKeywords("all user list"); //种类 $objPHPExcel->getProperties()->setCategory("office document"); //设置当前的sheet $objPHPExcel->setActiveSheetIndex(0); //设置表头 $objPHPExcel->getActiveSheet()->setCellValue('A1', "用户名"); $objPHPExcel->getActiveSheet()->setCellValue('B1', "密码"); $objPHPExcel->getActiveSheet()->setCellValue('C1', "邮箱"); $objPHPExcel->getActiveSheet()->setCellValue('D1', "电话"); $objPHPExcel->getActiveSheet()->setCellValue('E1', "真实姓名"); $objPHPExcel->getActiveSheet()->setCellValue('F1', "注册时间"); $objPHPExcel->getActiveSheet()->setCellValue('G1', "ip来源"); $sql = "SELECT * FROM user"; 查询数据库所有数据 $res = $nsodb -> get_results($sql,ARRAY_A); foreach($res as $key=>$val){ 把结果集进行遍历一行一行写入excel $key+=2; $objPHPExcel->getActiveSheet()->setCellValue('A'.$key, $val['uid']); $objPHPExcel->getActiveSheet()->setCellValue('B'.$key, $val['password']); $objPHPExcel->getActiveSheet()->setCellValue('C'.$key, $val['mail']); $objPHPExcel->getActiveSheet()->setCellValue('D'.$key, $val['phone']); $objPHPExcel->getActiveSheet()->setCellValue('E'.$key, $val['name']); $objPHPExcel->getActiveSheet()->setCellValue('F'.$key, $val['add_time']); $objPHPExcel->getActiveSheet()->setCellValue('G'.$key, $val['ipaddress']); } // 高置列的宽度 $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(30); $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(30); $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(30); $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(30); $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(30); $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(30); $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(30); ob_end_clean(); //清除缓存防止乱码 header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header('Content-Disposition: attachment;filename="alluser.xlsx"'); //设置excel 文件名 header('Cache-Control: max-age=0'); $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007'); $objWriter->save('php://output'); //保存 exit;?>