laravel 导入导出有很多 但是你发现等你根据conposer安装excal的时候你发现 他总是不依不饶的提示你: 安装失败
1. 在laravel 项目的根目录下 我们会看到 一个composer.json的文件:
打开, 并找到 "maatwebsite/excel": "~2.0.0" 修改为 "~2.1.0" 保存
如果在composer.json找不到,复制粘贴到以下位置: require里
2. 执行 composer update maatwebsite/excel
3. 编辑 laravel config/app.php
找到 provides 的数组 在数组中添加 Maatwebsite\Excel\ExcelServiceProvider::class,
在 aliases 的数组 中 添加 'Excel' => Maatwebsite\Excel\Facades\Excel::class,
4. 添加完成之后 执行: php artisan vendor:publish
这样就可以建路由 Controller 等
<?php
namespace App\Http\Controllers\managers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\models\User; //用户表
use Illuminate\Support\Facades\DB;
use Excel; //excel
use Illuminate\Support\Facades\Storage; //本地驱动
//导出实例
public function Push(){
$info =DB::table('admin_user')->get(); //获取用户表数据
$info = json_encode($info);
$info = json_decode($info,true);
$cellData =['id','用户名','密码','登录时间','退出时间','ip']; //数据库字段
array_unshift($info,$cellData);
Excel::create(iconv('UTF-8', 'GBK', '后台表'),function($excel) use ($info){
$excel->sheet('sheetname', function($sheet) use ($info){
$sheet->rows($info);
});
})->store('xls')->export('xls');
}
//导入实例
public function addExcel(Request $request){
if ($request->isMethod('post')) {
$fileCharater = $request->file('source');
if ($fileCharater->isValid()) { //括号里面的是必须加的哦
//如果括号里面的不加上的话,下面的方法也无法调用的
//获取文件的扩展名
$ext = $fileCharater->getClientOriginalExtension();
//获取文件的绝对路径
$path = $fileCharater->getRealPath();
//定义文件名
$filename = date('Y-m-d-h-i-s').'.'.$ext;
// Storage/app/public 本地驱动 获取磁盘实例
//存储文件。disk里面的public。总的来说,就是调用disk模块里的public配置
$bool=Storage::disk('public')->put($filename, file_get_contents($path));
$filePath = 'storage/app/public/'.iconv('UTF-8', 'GBK', $filename);
Excel::load($filePath,function ($reader){
$reader = $reader->getSheet(0);
$data = $reader->toArray();
for($i=1;$i<count($data);$i++){
$array = array(
'username'=>$data[$i][1], //根据自己数据库中对应字段
'password'=>$data[$i][2],
'created_at'=>$data[$i][3],
'updated_at'=>$data[$i][4],
'ip'=>$data[$i][5],
);
$info=User::insert($array); //新增
echo "导入成功";
}
});
}
}else{
return view('managers.addExcel');
}
}