Copy <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\NewClass;
use Excel;
class MaatwebsiteDemoController extends Controller
{
protected $model;
public function __construct(NewClass $model) {
$this->model = $model;
}
/**
* 指定前端頁面
*
* @var array
*/
public function importExport()
{
return view('importExport');
}
/**
* 導出並下載檔案
*
* @var array
*/
public function downloadExcel(Request $request, $type)
{
$data = $this->model->get()->toArray();
return Excel::create('testClass', function($excel) use ($data) {
$excel->sheet('mySheet', function($sheet) use ($data)
{
$sheet->fromArray($data);
});
})->download($type);
}
/**
* 導入資料到table
*
* @var array
*/
public function importExcel(Request $request)
{
if($request->hasFile('import_file')){
$path = $request->file('import_file')->getRealPath();
$data = Excel::load($path, function($reader) {})->get();
if(!empty($data) && $data->count()){
foreach ($data as $qqq) {
if(!empty($qqq)){
// 這邊就是你資料庫裡面所有的欄位設定
$insert[] = ['f_id' => $qqq['f_id'], 'name' => $qqq['name'],'pp_id'=> $qqq['pp_id']];
}
}
if(!empty($insert)){
// 將上面編排好的資料存到資料庫中
$this->model->insert($insert);
return back()->with('success','成功導入!');
}
}
}
return back()->with('error','導入失敗,請檢查你導入的檔案');
}
}