标签:str fun tor dimens attach type handle active font
1、方法封装
<?php /** * @description excel数据导出方法封装 列数支持700+ * @param array $title 列标题、宽度和数据字段 二维数组 必须 array(array(‘title‘=‘name‘,‘width‘=>30,‘field‘=>‘user_name‘),array(‘title‘=‘sex‘,‘width‘=>10,‘field‘=>‘sex‘)) * @param array $data 二维数组数据 必须 * @param string $fileName 导出文件名 * @param bool $bold 列标题是否加粗 */ function handleSheetData($title = array(), $data = array(), $fileName = ‘‘, $bold = true){ if (empty($title) || empty($data)) { return false; } $objPHPExcel = new PHPExcel(); $count = count($title); for ($i = 0; $i < $count; $i++) { $i_name = PHPExcel_Cell::stringFromColumnIndex($i);//处理列大于26个的方法 //设置列宽度 $objPHPExcel->getActiveSheet()->getColumnDimension($i_name)->setWidth($title[$i][‘width‘]); //设置列名 $objPHPExcel->setActiveSheetIndex(0)->setCellValue($i_name . ‘1‘, $title[$i][‘title‘]); //列名是否加粗 if ($bold) { $objPHPExcel->getActiveSheet()->getStyle($i_name . ‘1‘)->getFont()->setBold(true); } //数据处理 foreach ($data as $key => $item) { $objPHPExcel->setActiveSheetIndex(0)->setCellValue($i_name . ($key + 2), $item[$title[$i][‘field‘]]); } } $objPHPExcel->getActiveSheet()->setTitle(‘Simple‘); $objPHPExcel->setActiveSheetIndex(0); $fileName = $fileName ? $fileName : date("Ymd", time()) . ‘.xlsx‘; header(‘Content-Type: application/vnd.ms-excel‘); header(‘Content-Disposition: attachment;filename=‘ . $fileName); header(‘Cache-Control: max-age=0‘); header(‘Cache-Control: max-age=1‘); header(‘Expires: Mon, 26 Jul 1997 05:00:00 GMT‘); header(‘Last-Modified: ‘ . gmdate(‘D, d M Y H:i:s‘) . ‘ GMT‘); header(‘Cache-Control: cache, must-revalidate‘); header(‘Pragma: public‘); $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, ‘Excel2007‘); $objWriter->save(‘php://output‘); exit; } ?>
2、调用示例 data为二维数组数据
<?php $title = array( array(‘title‘=>‘Certificate name‘,‘width‘=>20,‘field‘=>‘cert_name‘), array(‘title‘=>‘Name‘,‘width‘=>30,‘field‘=>‘user_name‘), array(‘title‘=>‘Company‘,‘width‘=>30,‘field‘=>‘user_company‘), array(‘title‘=>‘Certificate ID‘,‘width‘=>30,‘field‘=>‘cert_key‘), array(‘title‘=>‘Effective date‘,‘width‘=>15,‘field‘=>‘effect_time‘), array(‘title‘=>‘Expiration time‘,‘width‘=>15,‘field‘=>‘expire_time‘), array(‘title‘=>‘Country‘,‘width‘=>30,‘field‘=>‘country‘), array(‘title‘=>‘Region‘,‘width‘=>15,‘field‘=>‘region‘), array(‘title‘=>‘SF_COMPANYCODE‘,‘width‘=>20,‘field‘=>‘SF_COMPANYCODE‘), array(‘title‘=>‘EMAIL‘,‘width‘=>30,‘field‘=>‘EMAIL‘), array(‘title‘=>‘COMPANYTYPE‘,‘width‘=>30,‘field‘=>‘COMPANYTYPE‘) ); handleSheetData($title,$data,‘Certificate_list_‘.date("Ymd", time()).‘.xlsx‘); ?>
标签:str fun tor dimens attach type handle active font
原文地址:https://www.cnblogs.com/guliang/p/12074182.html