首先要下载一个PHPExcel,有点大17.5M左右,不过里面东西不是全都要用。有demo可查看,有excel2007和其他版本excel之区分,这里没用excel2007
采用的是session传值,首先将查出来的内容 存到一个二维数组中,
在A页面中,将表名,表头,内容 全部存入session
在B页面中,即处理excel页面中接受session值进行写入表格
A.php 页面
function excel(){ $sql="select * from PMT_ERROR left join PMT_PR_NOTICE on PMT_PR_NOTICE.APP_UID=PMT_ERROR.APP_UID order by NOTICE_DATE desc"; $result = mysql_query($sql); $l=0; while($row = mysql_fetch_array($result)){ $l++; $data["$l"][1]=$l; $data["$l"][2]=$row['NOTICE_NAME']; $data["$l"][3]=$row['NOTICE_ID']; $data["$l"][4]=$row['ERROR_DES']; $data["$l"][5]=substr($row['ERROR_DATE'],0,10); } $title="项目异常信息"; $t_value=array('编号','项目名称','项目编号','终止原因','终止时间'); session_start(); $_SESSION[d_value]=$data; $_SESSION[t_value]=$t_value; $_SESSION[title]=$title; }
一个js触发导出
function output(){ location.href="B.php"; <?php excel(); ?> }
B页面
注意,PHPExcel.php 页面路径一定要正确,否则会报文件未被找到的错误,可以看下demo
<?php /** Error reporting */ error_reporting(E_ALL); header("Content-Type:text/html;charset=UTF-8"); date_default_timezone_set('Europe/London'); /** Include PHPExcel */ require_once('Classes/PHPExcel.php'); // Create new PHPExcel object $objPHPExcel = new PHPExcel(); // Set document properties $objPHPExcel->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"); //接受数据 session_start(); $title=$_SESSION['title']; $d_value=$_SESSION['d_value']; $t_value=$_SESSION['t_value']; //合并单元格,这里A1:H1不能用代码实现,头疼,会变成'?',不知道什么原因,暂时没处理成功$objPHPExcel->getActiveSheet()->mergeCells('A1:H1'); $objPHPExcel->getActiveSheet()->getStyle('A1') ->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER); // Add some data //打印题目 $objPHPExcel->setActiveSheetIndex(0) ->setCellValue("A1", "$title"); //打印表头 $j='A'; foreach($t_value as $value){ $objPHPExcel->setActiveSheetIndex(0) ->setCellValue($j."2", "$value"); $j++; } //打印内容 $i=2; foreach($d_value as $value1){ $i++; $j='A'; foreach($value1 as $value2){ $objPHPExcel->setActiveSheetIndex(0) ->setCellValue($j.$i, "$value2"); $j++; } } // 设置 worksheet 名字 $objPHPExcel->getActiveSheet()->setTitle('数据'); // 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="output.xls"');//修改excel的名字,用中文居然乱码。。。。 header('Cache-Control: max-age=0'); $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); $objWriter->save('php://output'); exit;