<?php /** * Created by PhpStorm. * User: Administrator * Date: 2018/9/19 * Time: 11:02 */ namespace think\custom\lib; /** * 导出类 * @author msw * Class Export * @package think\custom\common * 调用方法 * $export = new Export(); * $export->export_to_excel($title,$data,$name) * $title = array( * 0=>array('订单号','姓名','手机号') * ); * $data = array( * array('111','222','333'), * array('111','2223','3334'), * ); * $name = '未支付订单'; * */ class Export { public function export_to_excel($title,$data,$name=''){ $filename="$name".date('Y-m-d-').mt_rand(1000000,9999999).'.xlsx'; $data=array_merge($title,$data); $php_excel = new \PHPExcel(); $php_excel->setActiveSheetIndex(0); $php_sheet = $php_excel->getActiveSheet(); $php_sheet->setTitle('Sheet1'); $col_array = array("A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","AA","AB","AC","AD","AE","AF","AG","AH","AI","AJ","AK","AL","AM","AN","AO","AP","AQ","AR","AS","AT","AU","AV","AW","AX","AY","AZ",); $border = array( 'borders' => array ( 'outline' => array ( 'style' => \PHPExcel_Style_Border::BORDER_THIN, //设置border样式 'color' => array ('argb' => 'FF000000'), //设置border颜色 ), ),); foreach( $data as $k=>$value ){ $i=0; foreach( $value as $vk=>$vv ){ $php_sheet->setCellValue($col_array[$i].($k+1), $vv); $php_sheet->getStyle( $col_array[$i].($k+1))->applyFromArray($border); $i++; } } ob_end_clean();//清除缓冲区,避免乱码 try{ $php_writer = \PHPExcel_IOFactory::createWriter($php_excel,'Excel2007'); $dir="./static/".$filename; $php_writer->save($dir); return $dir; }catch (\Exception $e){ throw new \Exception($e->getMessage()); } } }
使用方法
public function export($title,$data,$name=''){ $Export = new Export(); $file = $Export->export_to_excel($title,$data,$name); return $file; }
// 生成 excel $file_url = $this->export($title,$_data['data'],$name);