使用PHPExcel导出ProcessWire页面数据
PHPExcel是个非常强大得Excel操作类,GIT地址:https://github.com/PHPOffice/PHPExcel/,需要注意得是这个项目已经停止维护了。
替代项目PhpSpreadsheet:https://github.com/PHPOffice/PhpSpreadsheet
下面这段代码展示了如何将processWire的数据全部导出至Excel中:
$pages_export = new PageArray(); //需要导出的数据集 $pages_export->import($page); /** Error reporting */ error_reporting(E_ALL); ini_set('display_errors', TRUE); ini_set('display_startup_errors', TRUE); date_default_timezone_set('Europe/London'); if (PHP_SAPI == 'cli') die('This example should only be run from a Web Browser'); /** Include PHPExcel */ require_once dirname(__FILE__) . './classes/phpexcel/PHPExcel.php'; // Create new PHPExcel object $objPHPExcel = new PHPExcel(); // Set document properties $objPHPExcel->getProperties()->setCreator("Julian Wong") ->setLastModifiedBy("Julian Wong") ->setTitle("BMS Export XLSX Document") ->setSubject("BMS Export XLSX Document") ->setDescription("export page data to xlsx document for Office 2007 XLSX, generated using PHP classes.") ->setKeywords("office 2007 openxml php") ->setCategory("result file"); $objPHPExcel->setActiveSheetIndex(0); // Field names in the first row $fields = $page->template->fields; $col = 0; foreach($fields as $f){ $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, 1, $f->label); $col++; } //Fetching the table data $row = 2; foreach($pages_export as $p) { $col = 0; foreach ($fields as $f) { $fname = $f->name; if($f->type == "FieldtypeOptions"){//特殊字段的处理 $data = array(); foreach ($p->$fname as $item) { $data[] = $item->title; } $fval = implode($data, "、"); }else{ //默认文本字段 $fval = $p->$fname; } $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $fval); $col++; } $row++; } // Rename 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="01simple.xls"'); header('Cache-Control: max-age=0'); // If you're serving to IE 9, then the following may be needed header('Cache-Control: max-age=1'); // If you're serving to IE over SSL, then the following may be needed 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($objPHPExcel, 'Excel5'); $objWriter->save('php://output'); exit;