本篇内容介绍了“怎么用php的lavarel框架导出文件”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
一、导出文件
1.创建一个干净的控制器 ExcelController.php :
php artisan make:controller ExcelController --plain
2.然后在 routes.php 中定义相关路由:
Route::get('excel/export','ExcelController@export'); Route::get('excel/import','ExcelController@import');
3.接下来在 ExcelController.php 中定义 export 方法实现导出功能:
<?php namespace App\Http\Controllers; use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Routing\Controller as BaseController; use Illuminate\Foundation\Validation\ValidatesRequests; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use PHPExcel;//引入excel类 use IOFactory; use DB; class ExcelController extends Controller { //导出 public function Excel(){ $query=DB::table('change')->get();//查询表 //print_r($query); if(!$query) return false;//判断是否为空值 $obj=new PHPExcel();//实例化excel类 include_once('../app/libs/PhpExcel/PHPExcel/IOFactory.php');//引入IOFactory.php $obj->getProperties()-> setTitle("export") ->setDescription("none"); $obj-> setActiveSheetIndex(0); $fields = DB::select("SHOW COLUMNS FROM `change`");//查询goods表中所有列名 //print_r($fields);die; $col = 0;//定义列 foreach($fields as $field){ $field =$field['Field']; $obj-> getActiveSheet() -> setCellValueByColumnAndRow($col, 1,$field); $col++; } $row = 2;//定义行 foreach($query as $data) { $col =0; foreach($fields as $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'); } }
“怎么用php的lavarel框架导出文件”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。