public function import($entity) { $appHelper = new libs\AppHelper(); $className = $appHelper->getNameSpace() . $entity; $model = new $className(); $table = $model->getTable(); $columns = \Schema::getColumnListing($table); $key = $model->getKeyName(); $notNullColumnNames = array(); $notNullColumnsList = \DB::select(\DB::raw("SHOW COLUMNS FROM `" . $table . "` where `Null` = 'no'")); if (!empty($notNullColumnsList)) { foreach ($notNullColumnsList as $notNullColumn) { $notNullColumnNames[] = $notNullColumn->Field; } } $status = \Input::get('status'); $filePath = null; if (\Input::hasFile('import_file') && \Input::file('import_file')->isValid()) { $filePath = \Input::file('import_file')->getRealPath(); } if ($filePath) { \Excel::load($filePath, function ($reader) use($model, $columns, $key, $status, $notNullColumnNames) { $this->importDataToDB($reader, $model, $columns, $key, $status, $notNullColumnNames); }); } $importMessage = $this->failed == true ? \Lang::get('panel::fields.importDataFailure') : \Lang::get('panel::fields.importDataSuccess'); return \Redirect::to('panel/' . $entity . '/all')->with('import_message', $importMessage); }
public function import(Request $request, UserRepository $userRepository, Bus $bus) { $filename = $request->file; $programId = $request->program_id; \Excel::load('storage/app/' . $filename, function ($reader) use($programId, $userRepository, $bus) { $sheets = $reader->all(); $sheets->each(function ($sheet) use($programId, $userRepository, $bus) { $sheet->each(function ($row) use($programId, $userRepository, $bus) { $student = Student::firstOrNew(['reg_no' => $row->nim]); $student->name = $row->nama; $student->entry_year = $row->tahun_masuk; $student->program_id = $programId; $user = $userRepository->findByUsername($student->reg_no); if (!$user) { $role = Role::where('name', 'Student')->first(); $roles = $role ? [$role->id] : []; $desc = ['password' => bcrypt($student->reg_no), 'name' => $student->name, 'active' => true]; $bus->dispatch(new RegisterNewUser($student->reg_no, $student->reg_no . '@email.com', $roles, $desc)); $user = $userRepository->findByUsername($student->reg_no); } $student->user_id = $user->id()->value(); $student->save(); }); }); }); return $this->formSuccess(route('admin.student.student.index'), ['message' => 'Import mahasiswa berhasil']); }
public function post() { $file = Input::file('grade'); \Excel::load($file->getRealPath(), function ($reader) { })->get(); return redirect()->back(); }
public function store(Request $request) { //dd('jajaja'); $file = $request->file('file'); //obtenemos el campo file obtenido por el formulario $nombre = $file->getClientOriginalName(); //indicamos que queremos guardar un nuevo archivo en el disco local \Storage::disk('local')->put($nombre, \File::get($file)); \Excel::load('/storage/public/files/' . $nombre, function ($archivo) use(&$falla) { $result = $archivo->get(); //leer todas las filas del archivo foreach ($result as $key => $value) { $var = new Periodo(); $datos = ['bloque' => $value->bloque, 'inicio' => $value->inicio, 'fin' => $value->fin]; $validator = Validator::make($datos, Periodo::storeRules()); if ($validator->fails()) { Session::flash('message', 'Los Periodos ya existen o el archivo ingresado no es valido'); $falla = true; } else { $var->fill($datos); $var->save(); } } })->get(); if ($falla) { // Fallo la validacion de algun campus, retornar al index con mensaje return redirect()->route('Administrador.periodos.index'); } \Storage::delete($nombre); Session::flash('message', 'Los Periodos fueron agregados exitosamente!'); return redirect()->route('Administrador.periodos.index'); }
public function import(Request $request, UserRepository $userRepository, Bus $bus) { $filename = $request->file; $programId = $request->program_id; \Excel::load('storage/app/' . $filename, function ($reader) use($programId, $userRepository, $bus) { $sheets = $reader->all(); $sheets->each(function ($sheet) use($programId, $userRepository, $bus) { $sheet->each(function ($row) use($programId, $userRepository, $bus) { $lecturer = Lecturer::firstOrNew(['reg_no' => $row->nidn_nup_nidk]); $lecturer->local_reg_no = $row->nip; $lecturer->name = $row->nama; $user = $userRepository->findByUsername($lecturer->reg_no); if (!$user) { $role = Role::where('name', 'Lecturer')->first(); $roles = $role ? [$role->id] : []; $desc = ['password' => bcrypt($lecturer->reg_no), 'name' => $lecturer->name, 'active' => true]; $bus->dispatch(new RegisterNewUser($lecturer->reg_no, $lecturer->reg_no . '@email.com', $roles, $desc)); $user = $userRepository->findByUsername($lecturer->reg_no); } $lecturer->user_id = $user->id()->value(); $lecturer->save(); }); }); }); return $this->formSuccess(route('admin.employee.lecturer.index'), ['message' => 'Import dosen berhasil']); }
public function Importprocess() { $uploaddata = array(); $StudentAdmissionData = Input::all(); $validation = Validator::make($StudentAdmissionData, ClassModel::$importrules); if ($validation->passes()) { if (!empty($StudentAdmissionData['importfile'])) { Input::file('importfile')->move('assets/uploads/grade/', 'grade' . Input::file('importfile')->getClientOriginalName()); $importfile = 'grade' . Input::file('importfile')->getClientOriginalName(); } $results = Excel::load('assets/uploads/grade/' . $importfile, function ($reader) { })->get()->toArray(); if (count(array_filter($results)) == 1) { $finaldata = $results[0]; } else { $finaldata = $results; } foreach ($finaldata as $final) { $GradeName = $final['grade']; if (!empty($GradeName)) { $count = ClassModel::where('GradeName', '=', $GradeName)->count(); if ($count == 0) { $ClassData['GradeName'] = $GradeName; ClassModel::create($ClassData); } } } return Redirect::to('class')->with('Message', 'Class Details Saved Succesfully'); } else { return Redirect::to('class')->withInput()->withErrors($validation->messages()); } }
public function postshopdata() { $file = Input::file('shopdata'); $destinationPath = 'importdata'; // If the uploads fail due to file system, you can try doing public_path().'/uploads' $filename = 'imported-shoppinglistdata'; //$filename = $file->getClientOriginalName(); //$extension =$file->getClientOriginalExtension(); $upload_success = Input::file('shopdata')->move($destinationPath, $filename . '.' . $file->getClientOriginalExtension()); if ($upload_success) { $importedFile = public_path() . '/importdata/' . $filename . '.' . $file->getClientOriginalExtension(); Excel::load($importedFile, function ($r) { $res = $r->all()->toArray(); foreach ($res as $data) { if ($data['kode'] != '' && $data['deskripsi'] != '' && $data['satuan'] != '' && $data['harga'] != '') { $d = new ShoppingList(); $d->kode_sl = $data['kode']; $d->deskripsi_pekerjaan = $data['deskripsi']; $d->satuan = $data['satuan']; $d->harga = $data['harga']; $d->save(); } } }); Session::flash('success', 'Shoppinglist Data imported to database'); return Redirect::to('/import'); } else { Session::flash('error', 'Error uploading files'); return Redirect::to('/import'); } }
public function postUpload() { $file = Input::file($this->input_name); $rstring = str_random(15); $destinationPath = realpath($this->upload_dir) . '/' . $rstring; $filename = $file->getClientOriginalName(); $filemime = $file->getMimeType(); $filesize = $file->getSize(); $extension = $file->getClientOriginalExtension(); //if you need extension of the file $filename = str_replace(Config::get('kickstart.invalidchars'), '-', $filename); $uploadSuccess = $file->move($destinationPath, $filename); $sheets = Excel::load($destinationPath . '/' . $filename)->calculate()->toArray(); $newsheets = array(); foreach ($sheets as $name => $sheet) { $newrows = array(); foreach ($sheet as $row) { if (implode('', $row) != '') { $rstr = str_random(5); $newrows[$rstr] = $row; } } $newsheets[$name] = $newrows; } file_put_contents(realpath($this->upload_dir) . '/' . $rstring . '.json', json_encode($newsheets)); return Redirect::to(strtolower($this->controller_name) . '/preview/' . $rstring); }
public function postBatch() { $file = Input::file('excel_file'); $result = Excel::load($file, function ($reader) { $reader->take(500); })->toArray(); $data = array_filter($result); if (isset($data[0][0]['vendor_id'])) { $data = $data[0]; } $i = 0; foreach ($data as $key => $value) { $cakes = new Cakes(); $cakes->vendor_id = $value['vendor_id']; $cakes->product_code = $value['product_code']; $cakes->title = $value['title']; $cakes->description = $value['description']; $cakes->type = $value['type']; $cakes->price = $value['price']; $cakes->availability = $value['availability']; $cakes->image = $value['image']; $cakes->city = $value['city']; if ($cakes->save()) { } else { $i++; } } if ($i) { return Redirect::to('/cake/index')->with('message', 'Error in cakes upload.'); } else { return Redirect::to('/cake/index')->with('message', 'Cakes upload succesfull.'); } }
public function uploadFile() { $importfile = Input::file('upload_ex_cik'); //$cik_no_change = array(); Excel::load($importfile, function ($reader) { $result = $reader->all(); $cik_no_change = array(); //$i=0; foreach ($result as $in) { if ($in['cik'] != "") { $ckj = $in['cik']; $ckj_details = Cik::where('name', $ckj)->first(); if ($ckj_details) { array_push($cik_no_change, $ckj); //$cik_no_change[$i]=$ckj; //$i=$i+1; } else { $ckj_details = new Cik(); $ckj_details->name = $ckj; $ckj_details->status = 0; $ckj_details->save(); } } } //print_r($cik_no_change); }); //$response = Response::json($cik_no_change); // return $response; $allUser = User::where('role_id', 1)->get(); return View::make('admin.adminDashboard')->withUser($allUser); }
public function store(Request $request) { //dd('jajaja'); $file = $request->file('file'); //obtenemos el campo file obtenido por el formulario $nombre = $file->getClientOriginalName(); //indicamos que queremos guardar un nuevo archivo en el disco local \Storage::disk('local')->put($nombre, \File::get($file)); $campus = $request->get('campus'); $tipos = $request->get('tipos'); \Excel::load('/storage/public/files/' . $nombre, function ($archivo) use($campus, $tipos) { $result = $archivo->get(); //leer todas las filas del archivo foreach ($result as $key => $value) { $campus = Campus::whereNombre($value->campus_id)->pluck('id'); $tipos = TipoSala::whereNombre($value->tipo_sala_id)->pluck('id'); //echo $facultades."<br>"; if (is_null($campus)) { // El campus no existe, deberia hacer algo para mitigar esto, o retornarlo al usuario ... } if (is_null($tipos)) { // El campus no existe, deberia hacer algo para mitigar esto, o retornarlo al usuario ... } //if(!Sala::whereNombre('campus_id',$campus)->whereNombre('tipo_sala_id',$tipos)->first()){ if (!Sala::where('nombre', $value->nombre)->first()) { $var = new Sala(); $var->fill(['nombre' => $value->nombre, 'descripcion' => $value->descripcion, 'capacidad' => $value->capacidad, 'campus_id' => $campus, 'tipo_sala_id' => $tipos]); $var->save(); } } })->get(); \Storage::delete($nombre); Session::flash('message', 'Las Salas fueron agregadas exitosamente!'); return redirect()->route('Encargado.salas.index'); }
public function index() { Excel::load('./excel/users.csv', function ($reader) { $results = $reader->get(); $results = $reader->all(); dd($results); }); }
/** * Show the form for creating a new resource. * * @return Response */ public function create() { // $value = null; Excel::load(storage_path() . '/001.xls', function ($reader) use(&$value) { $value = $reader->get()->toArray(); //object -> array }); return Redirect::action('CandidateController@store_a', ['data' => $value]); }
/** * @param FunctionalTester $I * @param Project $project * * @return void */ protected function _downloadExport(FunctionalTester $I, Project $project) { $response = $I->getJsonResponseContent(); $file = $response->file; if ($response->ext !== 'csv') { \Excel::load(storage_path('exports/' . $response->file))->store('csv'); unlink(storage_path('exports/' . $response->file)); $file = str_replace('.' . $response->ext, '.csv', $response->file); } $I->amOnAction('ProjectController@getDownloadExport', ['project' => $project, 'file' => $file]); }
public function LuuImportExcel(Request $req) { $v = \Validator::make($req->all(), ['fDiemExcel' => 'required|mimes:xls,xlsx']); if ($v->fails()) { return redirect()->back()->withErrors($v->errors()); } else { $luuden = storage_path() . '/ImportExcel/'; $taptin = Input::file('fDiemExcel'); //$extension = Input::file('fDiemExcel')->getClientOriginalExtension(); //Lấy tên và cả đuôi của tập tin $tenbandau = Input::file('fDiemExcel')->getClientOriginalName(); $upload_success = $taptin->move($luuden, $tenbandau); // Khi upload thành công thì thông báo if ($upload_success) { //Import vào CSDL //$sheet = Excel::load($luuden.'/'.$tenbandau, function($reader){})->get(); \Excel::load($luuden . '/' . $tenbandau, function ($reader) { //return $reader->dump(); trả về một đối tượng (Object) $results = $reader->toArray(); //Trả về mảng //return var_dump($results); $row = count($results); $n = count($results, 1); // Đếm từng phần tử trong mảng đa chiều $col = ($n - $row) / $row; // echo $col." :Số cột<br>".$row.": Số dòng<br>"; // echo $n." Số Phần tử của mảng 2 chiều (Gồm số phần tử của hàng và số phần tử của cột)"; for ($i = 1; $i < $row; $i++) { for ($j = 2; $j < $col - 2; $j++) { //echo $j.">"; //echo $results[$i][$j] . " "; if ($j >= 4 && $j < $col - 2) { //echo $results[$i][2]."-".$results[$i][$j]."<br>"; //Lưu điểm DB::table('chitiet_diem')->where('mssv', $results[$i][2])->update(['diem' => $results[$i][$j]]); } } echo "<br>"; } //Lưu nhận xét for ($i = 1; $i < $row; $i++) { DB::table('chia_nhom')->where('mssv', $results[$i][2])->update(['nhanxet' => $results[$i][$col - 2]]); echo $results[$i][2] . " => " . $results[$i][$col - 2] . "<br>"; } }); return Redirect::to('giangvien/nhapdiem')->with('BaoUpload', 'Import điểm từ tập tin Excel thành công!'); } else { return $upload_success; } } }
public function store(Request $request) { //dd('jajaja'); $file = $request->file('file'); //obtenemos el campo file obtenido por el formulario if (is_null($request->file('file'))) { Session::flash('message', 'Seleccion el archivo'); return redirect()->back(); } //obtenemos el campo file obtenido por el formulario $nombre = $file->getClientOriginalName(); //indicamos que queremos guardar un nuevo archivo en el disco local \Storage::disk('local')->put($nombre, \File::get($file)); $campus = $request->get('campus'); $tipos = $request->get('tipos'); $falla = false; \Excel::load('/storage/public/files/' . $nombre, function ($archivo) use(&$falla) { $result = $archivo->get(); //leer todas las filas del archivo foreach ($result as $key => $value) { $campus = Campus::whereNombre($value->campus_id)->pluck('id'); $tipos = TipoSala::whereNombre($value->tipo_sala_id)->pluck('id'); //echo $facultades."<br>"; if (is_null($campus)) { // El campus no existe, deberia hacer algo para mitigar esto, o retornarlo al usuario ... } if (is_null($tipos)) { // El campus no existe, deberia hacer algo para mitigar esto, o retornarlo al usuario ... } //if(!Sala::whereNombre('campus_id',$campus)->whereNombre('tipo_sala_id',$tipos)->first()){ $var = new Sala(); $datos = ['nombre' => $value->nombre, 'descripcion' => $value->descripcion, 'capacidad' => $value->capacidad, 'campus_id' => $campus, 'tipo_sala_id' => $tipos]; $validator = Validator::make($datos, Sala::storeRules()); if ($validator->fails()) { Session::flash('message', 'Las Salas ya existen o el archivo ingresado no es valido'); $falla = true; } else { $var->fill($datos); $var->save(); } } })->get(); if ($falla) { // Fallo la validacion de algun campus, retornar al index con mensaje return redirect()->route('Administrador.salas.index'); } \Storage::delete($nombre); Session::flash('message', 'Las Salas fueron agregadas exitosamente!'); return redirect()->route('Administrador.salas.index'); }
public function store(Request $request) { //dd('jajaja'); $file = $request->file('file'); //obtenemos el campo file obtenido por el formulario if (is_null($request->file('file'))) { Session::flash('message', 'Seleccion el archivo'); return redirect()->back(); } $nombre = $file->getClientOriginalName(); //indicamos que queremos guardar un nuevo archivo en el disco local \Storage::disk('local')->put($nombre, \File::get($file)); $asignaturas = $request->get('asignaturas'); $docentes = $request->get('docentes'); $falla = false; \Excel::load('/storage/public/files/' . $nombre, function ($archivo) use(&$falla) { $result = $archivo->get(); //leer todas las filas del archivo foreach ($result as $key => $value) { $asignaturas = Asignatura::whereNombre($value->asignatura_id)->pluck('id'); $docentes = Docente::whereNombres($value->docente_id)->pluck('id'); //echo $facultades."<br>"; if (is_null($asignaturas)) { // El campus no existe, deberia hacer algo para mitigar esto, o retornarlo al usuario ... } if (is_null($docentes)) { // El campus no existe, deberia hacer algo para mitigar esto, o retornarlo al usuario ... } //if(!Curso::whereNombre('asignatura_id',$asignaturas)->whereNombres('docente_id',$docentes)->first()){ $var = new Curso(); $datos = ['asignatura_id' => $asignaturas, 'docente_id' => $docentes, 'semestre' => $value->semestre, 'anio' => $value->anio, 'seccion' => $value->seccion]; $validator = Validator::make($datos, Curso::storeRules()); if ($validator->fails()) { Session::flash('message', 'Los Cursos ya existen o el archivo ingresado no es valido'); $falla = true; } else { $var->fill($datos); $var->save(); } } })->get(); if ($falla) { // Fallo la validacion de algun campus, retornar al index con mensaje return redirect()->route('Encargado.cursos.index'); } \Storage::delete($nombre); Session::flash('message', 'Los Cursos fueron agregados exitosamente!'); return redirect()->route('Encargado.cursos.index'); }
public function postBatchup() { $file = Input::file('excel_file'); $result = Excel::load($file, function ($reader) { $reader->take(500); })->toArray(); $data = array_filter($result); if (isset($data[0][0]['vendor_id'])) { $data = $data[0]; } foreach ($data as $key => $value) { //$validator = Validator::make($value,Product::$rules); //if($validator->passes()){ $venid = User::where('uniq_ven_id', '=', $value['vendor_id'])->get(array('id')); $already_product = Product::where('title', '=', $value['title'])->get(); if ($already_product->count()) { $prodvenrel = new Prodvenrelations(); $prodvenrel->vendor_id = $venid[0]->id; $prodvenrel->product_id = $already_product[0]->id; $prodvenrel->description = $value['description']; $prodvenrel->regular_price = $value['regular_price']; $prodvenrel->delux_price = $value['delux_price']; $prodvenrel->premium_price = $value['premium_price']; $prodvenrel->city = $value['city']; $prodvenrel->save(); $product = Product::where('id', '=', $already_product[0]->id)->first(); $product->ovid = $product->ovid . "," . $prodvenrel->id; $product->save(); } else { $product = new Product(); $product->category_id = $value['category_id']; $product->vendor_id = $venid[0]->id; $product->title = $value['title']; $product->description = $value['description']; //images in another batch up //just save the file paths $product->image = $value['image']; $product->regular_price = $value['regular_price']; $product->delux_price = $value['delux_price']; $product->premium_price = $value['premium_price']; $product->product_code = $value['product_code']; $product->city = $value['city']; $product->save(); } //} } return Redirect::to('admin/products/index')->with('message', 'Product created.'); }
public function handleOfficesImport() { $file = Input::file('file'); $folderPath = 'storage/offices/'; $fileName = $file->getClientOriginalName(); $file->move($folderPath, $fileName); $fileResults = Excel::load($folderPath . $fileName, function ($reader) { })->get(); $officesFromFile = array(); foreach ($fileResults as $fileResult) { foreach ($fileResult as $characteristicName => $characteristicValue) { if (isset($fileResult['Номер'])) { $officesFromFile[$fileResult['Номер']][$characteristicName] = $characteristicValue; } } } $translator = new GoogleTranslater(); foreach ($officesFromFile as $officeFromFile) { $city = City::with(array('region' => function ($query) use($officeFromFile) { $query->byTitle(trim($officeFromFile['Область']), 'ua'); }))->byTitle(trim($officeFromFile['Город']), 'ua')->first(); // create city if it doesn't exist if (!$city) { $region = Region::byTitle(trim($officeFromFile['Область']), 'ua')->first(); // get geo coordinates from Google API $geoAddress = 'Україна, ' . $region->title . ' обл., м. ' . trim($officeFromFile['Город']); $geoResult = json_decode(file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?' . http_build_query(array('address' => $geoAddress, 'sensor' => true))), true); $geoLatitude = $geoResult['results'][0]['geometry']['location']['lat']; $geoLongitude = $geoResult['results'][0]['geometry']['location']['lng']; // create city entity $city = City::create(array('id_region' => $region->id, 'title' => trim($officeFromFile['Город']), 'title_ru' => trim($officeFromFile['Город (рус)']), 'title_en' => $translator->translateText(trim($officeFromFile['Город']), "uk", "en"), 'latitude' => isset($geoLatitude) && $geoLatitude ? $geoLatitude : '', 'longitude' => isset($geoLongitude) && $geoLongitude ? $geoLongitude : '', 'is_active' => 1)); if (!$city) { return Response::json(array('status' => false)); } } $officeData = array('id_city' => $city->id, 'number' => trim($officeFromFile['Номер']), 'address' => trim($officeFromFile['Адрес']), 'address_ru' => trim($officeFromFile['Адрес (рус)']), 'address_en' => $translator->translateText(trim($officeFromFile['Адрес']), "uk", "en") ?: '', 'title' => trim($officeFromFile['Название']), 'title_ru' => trim($officeFromFile['Название (рус)']), 'title_en' => $translator->translateText(trim($officeFromFile['Название']), "uk", "en") ?: '', 'description' => trim($officeFromFile['Описание']), 'description_ru' => trim($officeFromFile['Описание (рус)']), 'description_en' => $translator->translateText(trim($officeFromFile['Описание']), "uk", "en") ?: '', 'metro' => trim($officeFromFile['Станции метро']), 'metro_ru' => trim($officeFromFile['Станции метро (рус)']), 'metro_en' => $translator->translateText(trim($officeFromFile['Станции метро']), "uk", "en") ?: '', 'latitude' => trim($officeFromFile['Latitude']), 'longitude' => trim($officeFromFile['Longitude']), 'phones' => trim($officeFromFile['Телефоны']), 'director' => trim($officeFromFile['Директор']), 'director_ru' => trim($officeFromFile['Директор (рус)']), 'director_en' => $translator->translateText(trim($officeFromFile['Директор']), "uk", "en") ?: '', 'services' => trim($officeFromFile['Услуги']), 'services_ru' => trim($officeFromFile['Услуги (рус)']), 'services_en' => $translator->translateText(trim($officeFromFile['Услуги']), "uk", "en") ?: '', 'type' => str_replace(';', ',', trim($officeFromFile['Тип'])), 'atm_type' => str_replace(';', ',', trim($officeFromFile['Тип банкомата'])), 'atm_subtype' => str_replace(';', ',', trim($officeFromFile['Подтип банкомата'])), 'is_active' => trim($officeFromFile['Активность']) == 'Да' ? 1 : 0, 'schedule' => trim($officeFromFile['Режим работы']), 'schedule_ru' => $translator->translateText(trim($officeFromFile['Режим работы']), "uk", "ru") ?: '', 'schedule_en' => $translator->translateText(trim($officeFromFile['Режим работы']), "uk", "en") ?: '', 'schedule_operations' => trim($officeFromFile['Операционная касса']), 'schedule_operations_ru' => $translator->translateText(trim($officeFromFile['Операционная касса']), "uk", "ru") ?: '', 'schedule_operations_en' => $translator->translateText(trim($officeFromFile['Операционная касса']), "uk", "en") ?: '', 'schedule_operations_post' => trim($officeFromFile['Послеоперационная касса']), 'schedule_operations_post_ru' => $translator->translateText(trim($officeFromFile['Послеоперационная касса']), "uk", "ru") ?: '', 'schedule_operations_post_en' => $translator->translateText(trim($officeFromFile['Послеоперационная касса']), "uk", "en") ?: ''); $existedOffice = Office::byNumber(trim($officeFromFile['Номер']))->first(); if (!$existedOffice) { Office::create($officeData); } else { Office::where('number', trim($officeFromFile['Номер']))->update($officeData); } } return Response::json(array('status' => true)); }
public function persist() { $filename = $this->moveToLocalStorage($this->file('doctor-information')); \Excel::load(storage_path('app/doctor-information/' . $filename), function (LaravelExcelReader $reader) { $result = $reader->get(); foreach ($result as $row) { $param = ['name' => $row['姓名'], 'type' => substr(trim($row['等级']), 0, 1), 'level' => 5, 'hospital' => $row['所属医院'], 'hospital_level' => $row['医院级别'], 'department' => $row['科室'], 'phone' => strval(intval($row['注册电话'])), 'referred_name' => $row['推荐代表'], 'referred_phone' => strval(intval($row['代表电话'])), 'region' => $row['区域9大区'], 'region_level' => $row['销售大区级别'], 'responsible' => $row['销售地区级别']]; if ($customer = Customer::where('phone', strval(intval($row['注册电话'])))->first()) { $param['customer_id'] = $customer->id; } if ($customer_info = CustomerInformation::where('phone', strval(intval($row['注册电话'])))->first()) { $customer_info->update($param); return; } CustomerInformation::create($param); } }); }
public function store(Request $request) { //dd('jajaja'); $file = $request->file('file'); $file = $request->file('file'); //obtenemos el campo file obtenido por el formulario if (is_null($request->file('file'))) { Session::flash('message', 'Seleccion el archivo'); return redirect()->back(); } //obtenemos el campo file obtenido por el formulario $nombre = $file->getClientOriginalName(); //indicamos que queremos guardar un nuevo archivo en el disco local \Storage::disk('local')->put($nombre, \File::get($file)); $carreras = $request->get('carreras'); $falla = false; \Excel::load('/storage/public/files/' . $nombre, function ($archivo) use(&$falla) { $result = $archivo->get(); //leer todas las filas del archivo foreach ($result as $key => $value) { $carreras = Carrera::whereNombre($value->carrera_id)->pluck('id'); if (is_null($carreras)) { // El campus no existe, deberia hacer algo para mitigar esto, o retornarlo al usuario ... } $var = new Estudiante(); $datos = ['rut' => $value->rut, 'nombres' => $value->nombres, 'apellidos' => $value->apellidos, 'email' => $value->email, 'carrera_id' => $carreras]; $validator = Validator::make($datos, Estudiante::storeRules()); if ($validator->fails()) { Session::flash('message', 'Los Estudiantes ya existen o el archivo ingresado no es valido'); $falla = true; } else { $var->fill($datos); $var->save(); } } })->get(); if ($falla) { // Fallo la validacion de algun campus, retornar al index con mensaje return redirect()->route('Encargado.estudiantes.index'); } \Storage::delete($nombre); Session::flash('message', 'Los Estudiantes fueron agregados exitosamente!'); return redirect()->route('Encargado.estudiantes.index'); }
public function postMasivo(Requests\ExcelFilesRequest $request) { $file = $request->file('excel'); $path = $file->getRealPath(); $return = ['error' => false]; \Excel::load($path, function ($reader) use(&$return) { // Getting all results $results = $reader->get(); $sheet = $reader->first(); foreach ($sheet as $row) { dd($row); $validator = Validator::make($row, ['0' => 'required', '1' => 'required|unique:contr,rfc']); if ($validator->fails()) { $return['error'] = true; $return['mesages'] = $validator; return false; } } }); }
function do_upload() { if (Input::hasFile('fileupload')) { $image = Input::file('fileupload'); $filename = $image->getClientOriginalName(); $image->move($this->path, $filename); Excel::load($this->path . $filename, function ($reader) { $result = $reader->get(); // var_dump($reader->nama); foreach ($result as $key => $value) { $getemail = $this->receiver->get_email($value->email); if (count($getemail) == 0) { if ($value->email != NULL) { $insert['receiver_name'] = $value->nama == NULL ? "" : $value->nama; $insert['receiver_email'] = $value->email == NULL ? "" : $value->email; $insert['receiver_region'] = $value->kota == NULL ? "" : $value->kota; $insert['receiver_company'] = $value->perusahaan == NULL ? "" : $value->perusahaan; $insert['receiver_position'] = $value->jabatan == NULL ? "" : $value->jabatan; $insert['receiver_purpose'] = $value->tujuan == NULL ? "" : $value->tujuan; $insert['receiver_nature_business'] = $value->nature_business == NULL ? "" : $value->nature_business; $insert['receiver_country'] = $value->negara == NULL ? "" : $value->negara; $insert['receiver_phone'] = $value->telepon == NULL ? "" : $value->telepon; $insert['receiver_address'] = $value->alamat == NULL ? "" : $value->alamat; $insert['receiver_business'] = $value->bidang == NULL ? "" : $value->bidang; $insert['receiver_interest_product'] = $value->interest_product == NULL ? "" : $value->interest_product; $insert['receiver_source_information'] = $value->source_information == NULL ? "" : $value->source_information; $insert['receiver_status'] = 1; $insert['created_at'] = date('Y-m-d H:i:s'); $this->receiver->add($insert); } } } // echo $reader->dump(); }); Session::flash('notip', '<div class="alert alert-success">Data receiver berhasil diimport</div>'); return Redirect::to('/blast/receiver/list'); } else { Session::flash('notip', '<div class="alert alert-danger">File Tidak Ada</div>'); return Redirect::to('/blast/receiver/list'); } }
public function store(Request $request) { //dd('jajaja'); $file = $request->file('file'); //obtenemos el campo file obtenido por el formulario if (is_null($request->file('file'))) { Session::flash('message', 'Seleccion el archivo'); return redirect()->back(); } $nombre = $file->getClientOriginalName(); //obtenemos el nobmre del archivo \Storage::disk('local')->put($nombre, \File::get($file)); //indicamos que queremos guardar un //nuevo archivo en el disco local $falla = false; \Excel::load('/storage/public/files/' . $nombre, function ($archivo) use(&$falla) { $result = $archivo->get(); //leer todas las filas del archivo // if fichero es valido => iterar con el foreach foreach ($result as $key => $value) { //if(!Campus::where('nombre',$value->nombre)->first()){ $var = new Campus(); $datos = ['nombre' => $value->nombre, 'direccion' => $value->direccion, 'latitud' => $value->latitud, 'longitud' => $value->longitud, 'descripcion' => $value->descripcion, 'rut_encargado' => $value->rut_encargado]; $validator = Validator::make($datos, Campus::storeRules()); if ($validator->fails()) { Session::flash('message', 'Los Campus ya existen o el archivo ingresado no es valido'); $falla = true; } else { $var->fill($datos); $var->save(); } } })->get(); if ($falla) { // Fallo la validacion de algun campus, retornar al index con mensaje return redirect()->route('Administrador.campus.index'); } \Storage::delete($nombre); Session::flash('message', 'Los Campus fueron agregados exitosamente!'); return redirect()->route('Administrador.campus.index'); }
public function store(Request $request) { //dd('jajaja'); $file = $request->file('file'); //obtenemos el campo file obtenido por el formulario $nombre = $file->getClientOriginalName(); //indicamos que queremos guardar un nuevo archivo en el disco local \Storage::disk('local')->put($nombre, \File::get($file)); \Excel::load('/storage/public/files/' . $nombre, function ($archivo) { $result = $archivo->get(); //leer todas las filas del archivo foreach ($result as $key => $value) { $var = new Asignatura(); $var->fill(['nombre' => $value->nombre, 'descripcion' => $value->descripcion]); $var->save(); } })->get(); \Storage::delete($nombre); Session::flash('message', 'Los periodos fueron agregados exitosamente!'); return redirect()->route('Administrador.roles.index'); }
public function store(Request $request) { //dd('jajaja'); $file = $request->file('file'); //obtenemos el campo file obtenido por el formulario $nombre = $file->getClientOriginalName(); $cursos = $request->get('cursos'); $salas = $request->get('salas'); $periodos = $request->get('periodos'); //indicamos que queremos guardar un nuevo archivo en el disco local \Storage::disk('local')->put($nombre, \File::get($file)); \Excel::load('/storage/public/files/' . $nombre, function ($archivo) use($cursos, $salas, $periodos) { $result = $archivo->get(); //leer todas las filas del archivo foreach ($result as $key => $value) { $salas = Sala::whereNombre($value->sala_id)->pluck('id'); $periodos = Periodo::whereBloque($value->periodo_id)->pluck('id'); $cursos = Curso::where('seccion', $value->curso_id)->pluck('id'); if (is_null($salas)) { // El campus no existe, deberia hacer algo para mitigar esto, o retornarlo al usuario ... } if (is_null($periodos)) { // El campus no existe, deberia hacer algo para mitigar esto, o retornarlo al usuario ... } if (is_null($cursos)) { // El campus no existe, deberia hacer algo para mitigar esto, o retornarlo al usuario ... } if (!Horario::where('sala_id', $salas)->where('periodo_id', $periodos)->where('curso_id', $cursos)->first()) { $var = new Horario(); $var->fill(['fecha' => $value->fecha, 'sala_id' => $salas, 'periodo_id' => $periodos, 'curso_id' => $cursos]); $var->save(); } } })->get(); \Storage::delete($nombre); Session::flash('message', 'Los Horarios fueron agregados exitosamente!'); return redirect()->route('Administrador.horarios.index'); }
/** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $radio_congvan = $request->input('radio_congvan'); // xu ly file /* if($request->hasFile('attachment')) { $file = $request->file('attachment'); $newnamefile = File::savefile($file, Auth::user()->id); } */ if ($radio_congvan == 'congvandi') { } else { if ($radio_congvan == 'congvanden') { } else { if ($radio_congvan == 'congvandenbo') { //protected $delimiter = ','; /* \Excel::filter('chunk')->load(storage_path('uploads/21_09_2015_191_xin2.csv'))->chunk(250, function($results) { $results->toArray(); foreach ($results as $row) { dd($row);//->dd(); } }); */ \Excel::load(storage_path('uploads/final.csv'), function ($reader) { //$reader->dd(); // Getting all results $results = $reader->get(); // ->all() is a wrapper for ->get() and will work the same $results = $reader->all(); dd($results); }, 'UTF-8'); } } } }
| | Here is where you can register all of the routes for an application. | It's a breeze. Simply tell Laravel the URIs it should respond to | and give it the Closure to execute when that URI is requested. | */ Route::get('/', function () { return View::make('fronts.login'); }); Route::get('/sl', function () { Excel::load('importdata/sl.xls', function ($r) { $res = $r->all()->toArray(); foreach ($res as $data) { $d = new ShoppingList(); $d->kode_sl = $data['kode_sl']; $d->deskripsi_pekerjaan = $data['deskripsi_pekerjaan']; $d->satuan = $data['satuan']; $d->harga = $data['harga']; $d->save(); } }); }); Route::post('/auth', 'SessionController@auth'); Route::get('/logout', 'SessionController@logout'); Route::group(array('prefix' => 'home', 'before' => 'auth'), function () { Route::get('/', 'HomeController@dash'); }); Route::group(array('prefix' => 'users', 'before' => 'auth'), function () { Route::get('/', 'UserController@data'); Route::post('/submit', 'UserController@submit'); Route::get('/{id}/edit', 'UserController@edit');
/** * Execute the console command. * * @return mixed */ public function handle() { $this->info('0%: Se comenzó a importar el excel.'); $languages = \Solunes\Master\App\Language::get(); \Excel::load(public_path('seed/import.xls'), function ($reader) use($languages) { foreach ($reader->get() as $sheet) { $sheet_model = $sheet->getTitle(); if ($node = \Solunes\Master\App\Node::where('name', $sheet_model)->first()) { $field_array = []; $field_sub_array = []; $sub_field_insert = []; foreach ($languages as $language) { foreach ($node->fields()->whereNotIn('type', ['child', 'subchild', 'field'])->get() as $field) { if ($language->id > 1) { $field_array[$field->name . '_' . $language->code] = $field; } else { $field_array[$field->name] = $field; } } } foreach ($node->fields()->where('type', 'field')->get() as $field) { $field_sub_array[$field->name] = $field; } $sheet->each(function ($row) use($languages, $node, $field_array, $field_sub_array, $sub_field_insert) { $new_item = false; foreach ($row->all() as $column => $input) { if ($column == 'id' && $input) { $model = \FuncNode::node_check_model($node); if (!($item = $model->where('id', $row->id)->first())) { $item = $model; } $new_item = true; } if ($new_item && isset($field_array[$column])) { $field = $field_array[$column]; if ($column == $field->name) { $language_code = 'es'; } else { $language_code = str_replace($field->name . '_', '', $column); } if ($field->type == 'select' || $field->type == 'radio') { if ($subanswer = $field->field_options()->whereTranslation('label', $input)->first()) { $input = $subanswer->name; } else { $input = NULL; } } else { if ($field->type == 'checkbox') { $subinput = []; foreach (explode(' | ', $input) as $subval) { if ($subanswer = $field->field_options()->whereTranslation('label', $subval)->first()) { $subinput[] = $subanswer->name; } } if (count($subinput) > 0) { $input = json_encode($subinput); } else { $input = NULL; } } } if ($input || $input == '0') { if ($field->type == 'image' || $field->type == 'file') { $action_name = 'upload_' . $field->type; if ($field->multiple) { foreach (explode(' | ', $input) as $subinput) { $input_array[] = \Asset::$action_name(public_path('seed/' . $node->name . '/' . $subinput), $node->name . '-' . $field->name, true); } $input = json_encode($input_array); } else { $input = \Asset::$action_name(public_path('seed/' . $node->name . '/' . $input), $node->name . '-' . $field->name, true); } } $item = \FuncNode::put_data_field($item, $field, $input, $language_code); } } else { if ($new_item && isset($field_sub_array[$column])) { $field = $field_sub_array[$column]; if ($field->multiple) { $array_insert = []; foreach (explode(';', $input) as $value) { if (!is_numeric($value)) { $sub_model = \Solunes\Master\App\Node::where('table_name', $column)->first()->model; array_push($array_insert, $sub_model::where('name', $value)->first()->id); } else { array_push($array_insert, $value); } } } else { if (!is_numeric($input)) { $sub_model = \Solunes\Master\App\Node::where('table_name', $column)->first()->model; $array_insert = $sub_model::where('name', $input)->first()->id; } else { $array_insert = $input; } $array_insert = [$array_insert]; } $sub_field_insert[$column] = $array_insert; } } } if ($new_item) { $item->save(); foreach ($sub_field_insert as $column => $input) { $item->{$column}()->sync($input); } } }); } } }); $this->info('100%: Se agregaron los datos del excel.'); }
Route::get('excelr', function () { $reader = 'http://laravel5.com/fileentry/get/phpD3.tmp.xlsx'; $dataexcel = Excel::load($reader = 'storage\\app\\php6EA5.tmp.xlsx', function ($reader) { // dd($reader); // dd($reader->get());//xxx // dd($reader->all()[0]);//xx // echo get_class(get_class($reader->setActiveSheetIndex(0))); // var_dump(get_class_methods($reader->setActiveSheetIndex(0))); // dd($reader); // dd($reader->getExcel()->getSheet()); //xxx // dd($reader->setActiveSheetIndex(0)->getRowDimensions()); // dd($reader->setActiveSheetIndex(0)->getCellCollection()); // dd(get_class($reader->setActiveSheetIndex(0))); // $reader->setActiveSheetIndex(0)->getCell('G22')->getValue(); foreach ($reader->setActiveSheetIndex(0)->getCellCollection() as $sell) { // echo $reader->setActiveSheetIndexByName('2008-2009')->getCell($sell)->getValue().'<br>'; // $obj = $reader->setActiveSheetIndexByName('2008-2009')->getCell($sell)->getValue().'<br>'; $value = $reader->setActiveSheetIndexByName('Sheet1')->getCell($sell)->getValue(); // write data $reader->getActiveSheet()->setCellValue($sell, 'Agussss'); } // echo $reader->setActiveSheetIndexByName('2008-2009')->getCell('B'.'19')->getValue(); // dd($reader->all()[0]); // dd($reader->toObject());xxxx // $reader->setActiveSheetIndex(0); // $reader->getActiveSheet()->setCellValue('G22', 'Agussss') // ->setCellValue('C7', '5'); // $reader->createWriter($reader, 'Excel2007'); // $reader->create('Nimit New.xlsx')->store('xlsx'); })->setFileName('achmadi_BSSSSghfhfhfh')->save('xlsx'); // ->export('xlsx'); // ->get();//tidak bisa dipakai xxx