生成和读取EXCEL
<?php class TestAction extends Action { public function create() { require_once MIO_PATH.'Lib/PHPExcel/PHPExcel.php'; //require_once MIO_PATH.'Lib/PHPExcel/PHPExcel/Writer/Excel2007.php'; require_once MIO_PATH.'Lib/PHPExcel/PHPExcel/Writer/Excel5.php'; require_once MIO_PATH.'Lib/PHPExcel/PHPExcel/IOFactory.php'; $fileName = "test_excel"; $headArr = array("AAA啊","BBB哦","CCC额"); $data = array(array(1,2,'额'),array(1,3,'啊'),array(5,7,'额')); getExcel($fileName,$headArr,$data); } public function write() { require_once MIO_PATH.'Lib/PHPExcel/PHPExcel.php'; $fileName = './test.xls'; $filePath = $fileName; $PHPExcel = new PHPExcel(); $PHPReader = new PHPExcel_Reader_Excel5(); if(!$PHPReader->canRead($filePath)){ echo 'no Excel'; return ; } $PHPExcel = $PHPReader->load($filePath); $currentSheet = $PHPExcel->getSheet(0); $data = $currentSheet->toArray(null, true, true, true); dump($data); } } ?>
生成函数
function getExcel($fileName,$headArr,$data){ if(empty($data) || !is_array($data)){ die("data must be a array"); } if(empty($fileName)){ exit; } $date = date("Y_m_d",time()); $fileName .= "_{$date}.xls"; //创建新的PHPExcel对象 $objPHPExcel = new PHPExcel(); $objProps = $objPHPExcel->getProperties(); //设置表头 $key = ord("A"); foreach($headArr as $v){ $colum = chr($key); $objPHPExcel->setActiveSheetIndex(0) ->setCellValue($colum.'1', $v); $key += 1; } $column = 2; $objActSheet = $objPHPExcel->getActiveSheet(); foreach($data as $key => $rows){ //行写入 $span = ord("A"); foreach($rows as $keyName=>$value){// 列写入 $j = chr($span); $objActSheet->setCellValue($j.$column, $value); $span++; } $column++; } $fileName = iconv("utf-8", "gb2312", $fileName); //重命名表 $objPHPExcel->getActiveSheet()->setTitle('Simple'); //设置活动单指数到第一个表,所以Excel打开这是第一个表 $objPHPExcel->setActiveSheetIndex(0); //将输出重定向到一个客户端web浏览器(Excel2007) header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header("Content-Disposition: attachment; filename=\"$fileName\""); header('Cache-Control: max-age=0'); $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); ob_clean(); $objWriter->save('php://output'); exit; }