在开发框架的选择中,有些是可以和我们常用的软件结合使用。比如数据开发的框架,能结合mysql的使用。本篇所要讲的lavarel框架,能够实现对excel的导入和导出。也就是说,我们能够使用lavarel处理一些表格数据的事务。下面就lavarel框架导出文件的步骤带来详细介绍。
一、导出文件
1.创建一个干净的控制器 ExcelController.php :
phpartisanmake:controllerExcelController--plain
2.然后在 routes.php 中定义相关路由:
Route::get('excel/export','ExcelController@export'); Route::get('excel/import','ExcelController@import');
3.接下来在 ExcelController.php 中定义 export 方法实现导出功能:
<?php namespaceApp\Http\Controllers; useIlluminate\Foundation\Bus\DispatchesJobs; useIlluminate\Routing\ControllerasBaseController; useIlluminate\Foundation\Validation\ValidatesRequests; useIlluminate\Foundation\Auth\Access\AuthorizesRequests; usePHPExcel;//引入excel类 useIOFactory; useDB; classExcelControllerextendsController { //导出 publicfunctionExcel(){ $query=DB::table('change')->get();//查询表 //print_r($query); if(!$query)returnfalse;//判断是否为空值 $obj=newPHPExcel();//实例化excel类 include_once('../app/libs/PhpExcel/PHPExcel/IOFactory.php');//引入IOFactory.php $obj->getProperties()->setTitle("export")->setDescription("none"); $obj->setActiveSheetIndex(0); $fields=DB::select("SHOWCOLUMNSFROM`change`");//查询goods表中所有列名 //print_r($fields);die; $col=0;//定义列 foreach($fieldsas$field){ $field=$field['Field']; $obj->getActiveSheet()->setCellValueByColumnAndRow($col,1,$field); $col++; } $row=2;//定义行 foreach($queryas$data) { $col=0; foreach($fieldsas$field) { //print_r($data); $field=$field['Field']; $obj->getActiveSheet()->setCellValueByColumnAndRow($col,$row,!empty($data["$field"])?$data["$field"]:''); $col++; } $row++; } $obj->setActiveSheetIndex(0); $objWriter=IOFactory::createWriter($obj,'Excel5'); header('Content-Type:application/vnd.ms-excel'); header('Content-Disposition:attachment;filename="Brand_'.date('Y-m-d').'.xls"'); header('Cache-Control:max-age=0'); $objWriter->save('php://output'); } }
二、导入文件
//Excel文件导入功能 publicfunctionimport() { $filePath='storage/exports/'.iconv('UTF-8','GBK','用户信息').'.xls'; Excel::load($filePath,function($reader){ $data=$reader->all(); dd($data); }); }