Exemplo n.º 1
2
 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 exportIt($return)
 {
     return parent::exportIt($return);
     $filename = $return['classname'] . "_" . date('Ymd');
     $xls = new Excel($filename);
     //$filename = $return['classname'] . "_" . date('Ymd') . ".xls";
     //header("Content-Disposition: attachment; filename=\"$filename\"");
     //header("Content-Type: application/vnd.ms-excel");
     //$flag = false;
     $xls->home();
     foreach ($return['objs'] as $key => $obj) {
         foreach ($obj as $name => $value) {
             $xls->label(Lang::t($name));
             $xls->right();
         }
         break;
     }
     $xls->down();
     //print("\n");
     foreach ($return['objs'] as $key => $obj) {
         $xls->home();
         foreach ($obj as $name => $value) {
             $xls->label($value);
             $xls->right();
         }
         $xls->down();
     }
     $xls->send();
     exit;
 }
Exemplo n.º 3
0
 public function downloadExcel()
 {
     include '/Data/ClassLib/Excel.class.php';
     $a = new \Excel();
     $a->set(array('A1' => 'test data'));
     $a->download('test');
 }
Exemplo n.º 4
0
 /**
  * 生成excel
  *
  * @param array $data
  */
 private function createExcel($data = array())
 {
     Language::read('export');
     import('libraries.excel');
     $excel_obj = new Excel();
     $excel_data = array();
     //设置样式
     $excel_obj->setStyle(array('id' => 's_title', 'Font' => array('FontName' => '宋体', 'Size' => '12', 'Bold' => '1')));
     //header
     $excel_data[0][] = array('styleid' => 's_title', 'data' => '订单编号');
     $excel_data[0][] = array('styleid' => 's_title', 'data' => '下单时间');
     $excel_data[0][] = array('styleid' => 's_title', 'data' => '付款时间');
     $excel_data[0][] = array('styleid' => 's_title', 'data' => '运费');
     $excel_data[0][] = array('styleid' => 's_title', 'data' => '物流单号');
     //data
     foreach ((array) $data as $k => $v) {
         $tmp = array();
         $tmp[] = array('data' => 'NC' . $v['order_sn']);
         $tmp[] = array('data' => date('Y-m-d H:i:s', $v['add_time']));
         $tmp[] = array('data' => $v['payment_time'] ? date('Y-m-d H:i:s', $v['payment_time']) : '');
         $tmp[] = array('format' => 'Number', 'data' => $v['shipping_fee']);
         $tmp[] = array('data' => $v['shipping_code']);
         $excel_data[] = $tmp;
     }
     $excel_data = $excel_obj->charset($excel_data, CHARSET);
     $excel_obj->addArray($excel_data);
     $excel_obj->addWorksheet($excel_obj->charset(L('exp_od_order'), CHARSET));
     $excel_obj->generateXML($excel_obj->charset(L('exp_od_order'), CHARSET) . $_GET['curpage'] . '-' . date('Y-m-d-H', time()));
 }
Exemplo n.º 5
0
 function onlogView($msg = '', $ty = '')
 {
     $action = "index.php?admin_log/logView";
     $hasLogViewPrivilege = $_ENV['menu']->checkPermission($this->ask_login_name, $_SERVER['QUERY_STRING'], "logView");
     $hasLogViewPrivilege['url'] = "?admin_main";
     $hasLogViewPrivilege['return'] = true;
     !$hasLogViewPrivilege['return'] && __msg($hasLogViewPrivilege);
     $LogTypeList = $this->ask_config->getLogType();
     $operator_list = $_ENV['operator']->getList(0, 0);
     $ConditionList['StartDate'] = isset($this->post['StartDate']) ? $this->post['StartDate'] : (isset($this->get[2]) ? $this->get[2] : date("Y-m-d", time()));
     $ConditionList['EndDate'] = isset($this->post['EndDate']) ? $this->post['EndDate'] : (isset($this->get[3]) ? $this->get[3] : date("Y-m-d", time()));
     $ConditionList['EndDate'] = min($ConditionList['EndDate'], date("Y-m-d", time()), date("Y-m-t", strtotime($ConditionList['StartDate'])));
     $ConditionList['operatorId'] = isset($this->post['operatorId']) ? intval(urldecode($this->post['operatorId'])) : (isset($this->get[4]) ? intval(urldecode($this->get[4])) : 0);
     $ConditionList['operator'] = !in_array($ConditionList['operatorId'], array(-2, -1, 0)) ? $operator_list[$ConditionList['operatorId']]['login_name'] : $ConditionList['operatorId'];
     $ConditionList['QuestionId'] = isset($this->post['QuestionId']) ? intval($this->post['QuestionId']) : (isset($this->get[5]) ? intval($this->get[5]) : 0);
     $ConditionList['log_type_id'] = isset($this->post['log_type_id']) ? intval(urldecode($this->post['log_type_id'])) : (isset($this->get[6]) ? intval(urldecode($this->get[6])) : 0);
     $ConditionList['AuthorName'] = isset($this->post['AuthorName']) ? trim(urldecode($this->post['AuthorName'])) : (isset($this->get[7]) ? trim(urldecode($this->get[7])) : '');
     $ConditionList['log_type'] = $ConditionList['log_type_id'] ? $LogTypeList[$ConditionList['log_type_id']] : $ConditionList['log_type_id'];
     @($page = max(1, intval($this->get[8])));
     $export = trim($this->get[9]) == "export" ? 1 : 0;
     $setting = $this->setting;
     if (!$export) {
         $pagesize = $this->setting['list_default'];
         $pagesize = 20;
         $log_list = $_ENV['log']->getLogList($ConditionList, $page, $pagesize);
         $departstr = page($log_list['LogCount'], $pagesize, $page, "admin_log/logView/" . $ConditionList['StartDate'] . "/" . $ConditionList['EndDate'] . "/" . urlencode($ConditionList['operatorId']) . "/" . $ConditionList['QuestionId'] . "/" . $ConditionList['log_type_id'] . "/" . urlencode($ConditionList['AuthorName']));
         $downloadstr = page_url("<下载EXCEL表格>", "admin_log/logView/" . $ConditionList['StartDate'] . "/" . $ConditionList['EndDate'] . "/" . urlencode($ConditionList['operatorId']) . "/" . $ConditionList['QuestionId'] . "/" . $ConditionList['log_type_id'] . "/" . urlencode($ConditionList['AuthorName']) . "/" . $page . "/export");
         $msg && ($message = $msg);
         $ty && ($type = $ty);
     } else {
         set_time_limit(0);
         $page = 1;
         $pagesize = 1000;
         $num = 1;
         require TIPASK_ROOT . '/lib/Excel.php';
         $oExcel = new Excel();
         $FileName = '操作日志表';
         $oExcel->download($FileName)->addSheet('日志表');
         //标题栏
         $title = array("日志ID", "对应问题ID", "用户名", "操作人", "操作时间", "日志内容");
         $oExcel->addRows(array($title));
         while ($num > 0) {
             $log_list = $_ENV['log']->getLogList($ConditionList, $page, $pagesize);
             foreach ($log_list['LogList'] as $key => $value) {
                 $value['message'] = htmlspecialchars_decode($value['message']);
                 $log_list['LogList'][$key]['message'] = preg_replace("/<(.*?)>/", "", $value['message']);
                 $excelArr = array("id" => $log_list['LogList'][$key]['id'], "qid" => $log_list['LogList'][$key]['qid'], "AuthorName" => $log_list['LogList'][$key]['AuthorName'], "user" => $log_list['LogList'][$key]['user'], "time" => date("Y-m-d H:i:s", $log_list['LogList'][$key]['time']), "message" => $log_list['LogList'][$key]['message']);
                 $oExcel->addRows(array($excelArr));
             }
             $page++;
             $num = count($order_list['OrderList']);
         }
         $oExcel->closeSheet()->close();
     }
     include template('logview', 'admin');
 }
Exemplo n.º 6
0
 /**
  * 导出excel表格
  */
 public static function exportFile($data, $type = 'xml', $fileName = 'excel-export')
 {
     if ($type == 'xml') {
         $xls = new Excel('UTF-8', false);
         $xls->addArray($data);
         $xls->generateXML($fileName);
     }
     if ($type == 'pdf') {
     }
     return;
 }
 /**
  * saveContants 
  * 存储通讯录
  * @access private
  * @return void
  */
 private function saveContants()
 {
     $ret = array("succ" => TRUE, "msg" => array());
     $excel = new Excel();
     $contantsArr = $excel->readExcel($this->_filePath, $this->_activeSheet, $this->_headers);
     foreach ($contantsArr['contents'] as $key => $contant) {
         if (FALSE === $this->contantsAddAttr($contant[0], $contant[1], $contant[2], $contant[3])) {
             $ret['msg'] = FALSE;
             array_push($ret['msg'], "{$contant[3]} 插入失败");
         }
     }
     return $ret;
 }
Exemplo n.º 8
0
 public function testOutput()
 {
     $this->specifyConfig()->cloneOnly(['excel', 'path']);
     $excel = new \Excel();
     $excel->worksheet('Worksheet', ['-']);
     $path = $this->savePath;
     $this->specify('save .xls to file', function () use($excel, $path) {
         $isExported = $excel->export('export.xls', $path);
         $this->assertTrue($isExported);
         $this->assertFileExists($path . 'export.xls');
     });
     $this->specify('save .xlsx to file', function () use($excel, $path) {
         $isExported = $excel->export('export.xlsx', $path);
         $this->assertTrue($isExported);
         $this->assertFileExists($path . 'export.xlsx');
     });
     $this->specify('save .html to file', function () use($excel, $path) {
         $isExported = $excel->export('export.html', $path);
         $this->assertTrue($isExported);
         $this->assertFileExists($path . 'export.html');
     });
     $this->specify('save .csv to file', function () use($excel, $path) {
         $isExported = $excel->export('export.csv', $path);
         $this->assertTrue($isExported);
         $this->assertFileExists($path . 'export.csv');
     });
     $this->specify('save .csv to not existing dir', function () use($excel, $path) {
         $isExported = $excel->export('export.csv', '/pmt/');
         $this->assertFalse($isExported);
         $this->assertFileNotExists('/pmt/export.csv');
     });
     $isExported = $excel->export();
     $this->assertTrue($isExported);
     $this->assertNotEmpty(ob_get_contents());
 }
Exemplo n.º 9
0
 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']);
 }
Exemplo n.º 10
0
 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');
     }
 }
Exemplo n.º 11
0
 public function postPurchases()
 {
     $input_start_date = \Input::get('start_date');
     if ($input_start_date == "") {
         $input_start_date = "01/01/1900";
     }
     $start_date = \DateTime::createFromFormat('d/m/Y', $input_start_date);
     $input_end_date = \Input::get('end_date');
     if ($input_end_date == "") {
         $end_date = new \DateTime("NOW");
     } else {
         $end_date = \DateTime::createFromFormat('d/m/Y', $input_end_date);
     }
     $data = UserPricelist::where('created_at', '>=', $start_date)->where('created_at', '<=', $end_date)->orderBy('created_at', 'desc')->get();
     if (count($data) == 0) {
         $errors = new \Illuminate\Support\MessageBag();
         $errors->add('downloadError', "There's no data within the dates specified.");
         return \Redirect::to('admin/purchases')->withErrors($errors);
     }
     \Excel::create('Redooor_Purchases_Report', function ($excel) use($data) {
         $excel->sheet('Purchases Report', function ($sheet) use($data) {
             $sheet->loadView('redminportal::reports/purchases')->with('data', $data);
         });
     })->download('csv');
 }
Exemplo n.º 12
0
 public function post()
 {
     $file = Input::file('grade');
     \Excel::load($file->getRealPath(), function ($reader) {
     })->get();
     return redirect()->back();
 }
Exemplo n.º 13
0
 public function fire()
 {
     $dir = $_SERVER['DOCUMENT_ROOT'] . "public/toUpload/";
     try {
         Excel::filter('chunk')->load($dir . 'data.xlsx')->chunk(250, function ($reader) {
             foreach ($reader->toArray() as $data) {
                 $user = User::where('identification_card', $data['cedula'])->first();
                 if (!$user) {
                     $user = User::create(['identification_card' => $data['cedula'], 'name' => $data['nombre'], 'user_name' => str_replace(' ', '.', $data['nombre']), 'email' => $data['email'] ? $data['email'] : 'Sin registro', 'address' => $data['direccion'] ? $data['direccion'] : 'Sin registro', 'residency_city' => $data['ciudad'] ? $data['ciudad'] : 'Sin registro', 'phone' => $data['tel1'] ? $data['tel1'] : 'Sin registro', 'mobile_phone' => $data['tel2'] ? $data['tel2'] : 'Sin registro', 'document_type' => 0, 'roles_id' => 4]);
                 }
                 $credit = CreditRequest::where('user_id', intval($user->id))->first();
                 if (!$credit) {
                     $c = new CreditRequest();
                     $c->user_id = intval($user->id);
                     $c->value = intval($data['limitecredito']);
                     $c->state = 1;
                     $c->location = 3;
                     $c->responsible = 18;
                     $c->save();
                 } else {
                     $credit->value = $data['limitecredito'];
                     $credit->save();
                 }
             }
         });
         echo $message = "El archivo  se ha guardado en la base de datos.";
     } catch (Exception $e) {
         echo $message = "No se ha guardar . Intenta subirlo de nuevo.";
     }
     Mail::send('emails.excel', ['msn' => $message], function ($m) use($message) {
         $m->to('*****@*****.**', 'Creditos Lilipink')->subject('Archivos actualizados');
     });
     array_map('unlink', glob($_SERVER['DOCUMENT_ROOT'] . "/toUpload/*"));
 }
Exemplo n.º 14
0
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function fire()
 {
     $dir = $_SERVER['DOCUMENT_ROOT'] . "public/toUpload/";
     $doc = $this->argument('table') . '.xlsx';
     try {
         Excel::filter('chunk')->load($dir . $doc)->chunk(250, function ($reader) {
             if ($this->argument('table') == 'extracts') {
                 Extract::insert($this->validate($reader));
             } else {
                 ExcelDaily::insert($this->validate($reader));
             }
         });
         $message = "El archivo " . $doc . " se ha guardado en la base de datos.";
     } catch (Exception $e) {
         $message = "No se ha guardar " . $doc . ". Intenta subirlo de nuevo.";
     }
     /*Mail::send('emails.excel', ['msn' => $message], function ($m) use($message){
     			$m->to('*****@*****.**', 'Creditos Lilipink')->subject('Notificación Lilipink');
     		});*/
     Mail::send('emails.excel', ['msn' => $message], function ($m) use($message) {
         $m->to('*****@*****.**', 'Creditos Lilipink')->subject('Notificación Lilipink');
     });
     unlink($dir . $doc);
     if (!is_dir($dir)) {
         rmdir($dir);
     }
 }
Exemplo n.º 15
0
 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);
 }
Exemplo n.º 16
0
 public static function Ajax($param)
 {
     switch ($param) {
         case 'byCategory':
             $id = e(Input::get('id'));
             $productos = Producto::where('categoria', "=", $id)->take(20)->get()->toJson();
             echo $productos;
             break;
         case 'excelByCategory':
             // print_r(Input::all());
             $catName = utf8_decode(utf8_encode(Input::get('catName')));
             $id = Input::get('id');
             $productos = Producto::where("categoria", "=", $id)->get()->toArray();
             $lista = self::formatExcel($productos);
             Excel::create("CAT" . $id, function ($excel) use($lista) {
                 $excel->sheet('productos', function ($sheet) use($lista) {
                     $sheet->fromArray($lista, null, 'A0', true);
                 });
             })->store('xls', public_path('/exports/categoria'));
             echo url("exports/categoria/CAT" . $id . ".xls");
             break;
         default:
             # code...
             break;
     }
 }
 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');
 }
Exemplo n.º 18
0
 public function makeSheet()
 {
     $input = Input::get('name');
     $arr = [];
     for ($i = 0; $i < 10; $i++) {
         $arr[$i] = [];
         for ($j = 0; $j < 10; $j++) {
             if ($i == $j) {
                 $arr[$i][$j] = "lol";
             } else {
                 $arr[$i][$j] = "hi";
             }
         }
     }
     \Excel::create($input, function ($excel) {
         global $input;
         $excel->setTitle("hello " . $input);
         $excel->sheet('Sheeeeet!', function ($sheet) {
             $sheet->cell('A1', function ($cell) {
                 $cell->setValue('hurr,');
             });
             $sheet->cell('A2', function ($cell) {
                 $cell->setValue('durr.');
             });
         });
     })->download('xls');
     // Won't work lol
     return View::make("excel", ["message" => "Did stuff " . $input . "!"]);
 }
 /**
  * Display a listing of the resource.
  *
  * @return Response
  */
 public function index()
 {
     /* $input = array_except(Input::all(), '_method');
     		$file_path = $input['excel_file']; */
     /* $target_dir = public_path()."\uploads\eod_data\\";
     		$target_file = $target_dir . basename($_FILES["excel_file"]["name"]); */
     //$target_file = 'C:\xampp\htdocs\sharemarket_app\uploads\eod_data\Copy (2) of fo28AUG2015bhav.csv';
     $target_file = 'uploads/eod_data/fo28AUG2015bhav - Copy (2).csv';
     //$target_file = 'C:\xampp\htdocs\sharemarket_app\uploads\eod_data\fo28AUG2015bhav - Copy.csv';
     /* if (move_uploaded_file($_FILES["excel_file"]["tmp_name"], $target_file)) {
     			echo "The file ". basename( $_FILES["excel_file"]["name"]). " has been uploaded.";
     		} else {
     			echo "Sorry, there was an error uploading your file.";
     			die;
     		} */
     set_time_limit(6000);
     $data = array();
     \Excel::filter('chunk')->load($target_file)->chunk(250, function ($results) use(&$data) {
         $results_array = $results->toArray();
         //print_r($results_array);
         $i = 1;
         foreach ($results_array as $row) {
             //print_r($row);die;
             $datetime = strtotime($row['expiry_dt']);
             $datetime *= 1000;
             $data[] = "[{$datetime}, {$row['open']}, {$row['high']}, {$row['low']}, {$row['close']}]";
             //print_r($data);die;
         }
         //print_r($data);die;
     });
     //print_r($data);
     //die;
     return View::make('eod.index')->with('data', $data);
 }
Exemplo n.º 20
0
 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);
 }
Exemplo n.º 21
0
 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.');
     }
 }
Exemplo n.º 22
0
 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']);
 }
Exemplo n.º 23
0
 public function indexToExcel($fecha_inicio, $fecha_fin)
 {
     $egresos = Egreso::whereBetween('fecha', [$fecha_inicio, $fecha_fin])->whereCuentaBancariaId(1)->withTrashed()->with('benef', 'proyectos.fondos', 'cuentaBancaria', 'user', 'ocs', 'solicitudes')->orderBy('fecha', 'DESC')->get();
     foreach ($egresos as $egreso) {
         !empty($egreso->cheque) ? $cheque_poliza = $egreso->cheque : ($cheque_poliza = $egreso->poliza);
         $proyectos = '';
         $fondos = '';
         if ($egreso->cuenta_id == 1 || $egreso->cuenta_id == 2) {
             foreach ($egreso->proyectos as $proyecto) {
                 $proyectos .= $proyecto->proyecto;
                 $fondos .= $proyecto->fondos[0]->fondo;
             }
         } else {
             $proyectos = '---';
             $fondos = '---';
         }
         $id_afin = '';
         if (count($egreso->solicitudes) > 0) {
             foreach ($egreso->solicitudes as $solicitud) {
                 $id_afin = $solicitud->no_afin;
             }
         }
         $arr_egresos[] = ['Cta. Bancaria' => $egreso->cuentaBancaria->cuenta_bancaria, 'Cheque/Póliza' => $cheque_poliza, 'Fecha' => $egreso->fecha_info, 'Beneficiario' => $egreso->benef->benef, 'Concepto' => $egreso->concepto, 'Monto' => $egreso->monto, 'Cuenta Clasificadora' => $egreso->cuenta->cuenta, 'Proyecto' => $proyectos, 'Fondo' => $fondos, 'ID AFIN' => $id_afin];
     }
     \Excel::create('Egresos', function ($excel) use($arr_egresos) {
         $excel->sheet('Jul-Sep', function ($sheet) use($arr_egresos) {
             $sheet->fromArray($arr_egresos);
         });
     })->download('xls');
 }
Exemplo n.º 24
0
 public static function getRelatorioOperacoes()
 {
     Excel::create('Planilha de Controle da Farmacia - Ocorrencias', function ($excel) {
         $excel->sheet('Ref. ', function ($sheet) {
             $sheet->mergeCells('A1:J5');
             $sheet->setHeight(1, 50);
             $sheet->row(1, function ($row) {
                 $row->setFontFamily('Arial');
                 $row->setFontSize(20);
             });
             $sheet->cell('A1', function ($cell) {
                 $cell->setAlignment('center');
             });
             $sheet->getStyle('D')->getAlignment()->setWrapText(true);
             $sheet->row(1, array('Frizelo Frigorificos Ltda.'));
             $periodo = explode('-', Input::get('periodo'));
             $a = [];
             foreach (Ocorrencia::whereBetween('data_hora', $periodo)->get() as $val) {
                 $a[] = ['Nome' => $val->colaborador->nome, 'Setor' => !empty($val->colaborador->setor->descricao) ? $val->colaborador->setor->descricao : null, 'Data' => $val->data_hora, 'Queixa' => empty($val->queixa->descricao) ? null : $val->queixa->descricao, 'Descrição / Motivo' => $val->relato . ' - ' . $val->diagnostico, 'Conduta / Destino' => $val->conduta . ' - ' . $val->destino];
             }
             $sheet->setAutoFilter('A6:J6');
             $sheet->setOrientation('landscape');
             $sheet->fromArray($a, null, 'A6', true);
         });
     })->export('xls');
 }
 public function report()
 {
     //add security to avoid stealing of information
     $user = Auth::user();
     $club = $user->Clubs()->FirstOrFail();
     $type = Input::get('expType');
     $from = date('Ymd', strtotime(Input::get('expFrom')));
     $to = date('Ymd', strtotime(Input::get('expTo')));
     $payments = Payment::where('club_id', '=', $club->id)->with('player')->whereBetween('created_at', array($from, $to))->get();
     $param = array('transaction_type' => 'cc', 'action_type' => 'refund,sale', 'condition' => 'pendingsettlement,complete,failed', 'club' => $club->id, 'start_date' => $from . '000000', 'end_date' => $to . '235959');
     $payment = new Payment();
     $transactions = $payment->ask($param);
     //return $transactions;
     //return json_decode(json_encode($transactions->transaction),true);
     // return View::make('export.lacrosse.accounting.all')
     // ->with('payments',  $transactions->transaction);
     //return json_decode(json_encode($transactions->transaction),true);
     Excel::create('transactions', function ($excel) use($transactions) {
         $excel->sheet('Sheetname', function ($sheet) use($transactions) {
             $sheet->setOrientation('landscape');
             // first row styling and writing content
             $sheet->loadView('export.lacrosse.accounting.all')->with('payments', $transactions->transaction);
         });
     })->download('xlsx');
 }
 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');
 }
Exemplo n.º 27
0
 protected function upload()
 {
     $validator = $this->fileValidator(Input::all());
     if ($validator->passes()) {
         if ($this->_user->download_count) {
             \Excel::selectSheetsByIndex(0)->load(Input::get('file'), function ($reader) {
                 $finalHtml = '';
                 $currentTime = date('d-m-Y_His');
                 mkdir($currentTime);
                 foreach ($reader->toArray() as $row) {
                     $html = "\n\t\t\t<style>\n\t\t\t\t.page-break {\n\t    \t\t\tpage-break-after: always;\n\t\t\t\t}\n\t\t\t\t.outer-container {\n\t\t\t\t\tmargin: 0% auto;\n\t\t\t\t\tborder: 1px solid black;\n\t\t\t\t\ttext-align: center;\n\t\t\t\t\theight: 99%;\n\t\t\t\t}\n\t\t\t\t.subject-container {\n\t\t\t\t\tfont-weight: bold;\n\t\t\t\t\tmargin-top: 30px;\n\t\t\t\t}\n\t\t\t\t.content-container {\n\t\t\t\t\ttext-align: left;\n\t\t\t\t\tpadding: 10px;\n\t\t\t\t\tmargin-top: 50px;\n\t\t\t\t}\n\t\t\t\tol {\n\t\t\t\t\ttext-align: left;\n\t\t\t\t}\n\t\t\t\tol li{\n\t\t\t\t\tpadding-bottom: 40px;\n\t\t\t\t}\n\t\t\t</style>\n\t\t\t<div class='outer-container'>\n\t\t\t\t\n\t\t\t \t\t<p class='subject-container'>Subject: NOTICE UNDER SECTION 138 OF NEGOTIABLE INSTRUMENT ACT READ WITH SECTION 420 OF INDIAN PENAL CODE</p>\n\n\t\t\t\t\t<p class='content-container'>\n\t\t\t\t\t\tOn behalf of and under instructions of my client <u>{$row['name']}</u> S/o__________ R/o __________ (hereinafter referred to as &quot;my client&quot;). I do hereby serve you with the following legal notice:\n\n\t\t\t\t\t\t<ol>\n\t\t\t\t\t\t\t<li>That my client, an engineering student, while looking for job paid Rs {$row['amount']} to you for assured placement in an MNC, last year.</li>\n\t\t\t\t\t\t\t<li>That thereafter my client issued a number of reminders to you for placement, but still no opportunity was provided to him, i.e. as you were unable to fulfill the promise as to placement of my client. Therefore, it was decided between you and my client that the amount of Rs {$row['amount']} should be refunded and as a result you issued him a cheque no {$row['cheque_number']} dated {$row['cheque_date']}.</li>\n\t\t\t\t\t\t\t<li>That the said cheque was presented by my client to State Bank of India, Noida for credit in his account in the month of December 2011 itself, but it bounced due to insufficient funds. And my client contacted you and was assured of cash in lieu of bounced cheque, therefore, my client did not take legal action earlier. My client thereafter again requested many a time to you for the payment of the said cheque amount by telephone and/or through personal visit of his representative, but in vain.</li>\n\t\t\t\t\t\t\t<li>That in April 2012, my client again tried depositing the cheque with State Bank of India, Mysore but it was again returned as unpaid with remarks &#45; Funds Insufficient, vide Syndicate Bank memo dated 19 April 2012.</li>\n\t\t\t\t\t\t\t<li>That in the facts and circumstances created by you my above said client left with no alternative except to serve you the present notice and calling upon all of you to make the payment of the above mentioned cheque amount totaling Rs {$row['amount']}/- (Rupees Ten Thousand only) including bouncing charges in cash with interest @ 24% per annum within 15 days of the receipt of this notice failing which my client shall be constrained to institute against you a criminal complaint under section 138 of the Negotiable Instrument Act read with section 420 of IPC where under you could be sentenced to undergo imprisonment of the two years and also pay the fine equivalent of the double amount of the above mentioned cheque as well as legal charges of this notice of Rs 2100/-</li>\n\t\t\t\t\t\t\t<li>That a copy of this notice retained in my office for further reference /record and legal action.</li>\n\t\t\t\t\t\t</ol>\n\t\t\t\t\t</p>\n\t\t\t</div>";
                     $finalHtml .= $html . "<div class='page-break'></div>";
                     \PDF::loadHTML($html)->setPaper('a4')->setOrientation('portrait')->setWarnings(false)->save($currentTime . '/' . $row["name"] . '_' . $row['cheque_number'] . '.pdf');
                 }
                 \PDF::loadHTML($finalHtml)->setPaper('a4')->setOrientation('portrait')->setWarnings(false)->save($currentTime . '/' . $currentTime . '.pdf');
                 // Here we choose the folder which will be used.
                 $dirName = public_path() . '/' . $currentTime;
                 // Choose a name for the archive.
                 $zipFileName = $this->_user->email . '_' . $currentTime . '.zip';
                 // Create ".zip" file in public directory of project.
                 $zip = new ZipArchive();
                 if ($zip->open(public_path() . '/' . $zipFileName, ZipArchive::CREATE) === TRUE) {
                     // Copy all the files from the folder and place them in the archive.
                     foreach (glob($dirName . '/*') as $fileName) {
                         $file = basename($fileName);
                         $zip->addFile($fileName, $file);
                     }
                     $zip->close();
                     $headers = array('Content-Type' => 'application/octet-stream');
                 } else {
                     echo 'failed';
                 }
                 $filename = $this->_user->email . '_' . $currentTime . '.zip';
                 $filepath = $_SERVER["DOCUMENT_ROOT"];
                 ob_start();
                 // http headers for zip downloads
                 header("Pragma: public");
                 header("Expires: 0");
                 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
                 header("Cache-Control: public");
                 header("Content-Description: File Transfer");
                 header("Content-type: application/octet-stream");
                 header("Content-Disposition: attachment; filename=\"" . $filename . "\"");
                 header("Content-Transfer-Encoding: binary");
                 header("Content-Length: " . filesize($filepath . "/" . $filename));
                 @readfile($filepath . "/" . $filename);
                 ob_end_flush();
                 \File::deleteDirectory($currentTime);
                 \File::delete($this->_user->email . '_' . $currentTime . '.zip');
                 // reader methods
                 $this->_user->download_count = $this->_user->download_count - 1;
                 $this->_user->save();
             });
         } else {
             return Redirect::to("home")->with('message', 'Your maximum download limit 3, exceeded in beta version.  Please subscribe to use this feature.');
         }
     }
     return Redirect::to("home")->withErrors($validator->messages());
 }
Exemplo n.º 28
0
 /**
  * Transmits the proper headers to cause a download to occur and to identify the file properly
  * @return nothing
  */
 function headers()
 {
     header("Content-Type: application/force-download");
     header("Content-Type: application/octet-stream");
     header("Content-Type: application/download");
     header("Content-Disposition: attachment;filename=" . Excel::filename($this->title) . ".xls ");
     header("Content-Transfer-Encoding: binary ");
 }
Exemplo n.º 29
0
 public function index()
 {
     Excel::load('./excel/users.csv', function ($reader) {
         $results = $reader->get();
         $results = $reader->all();
         dd($results);
     });
 }
Exemplo n.º 30
0
 public static function singleton()
 {
     if (!isset(self::$_instance)) {
         $c = __CLASS__;
         self::$_instance = new $c();
     }
     return self::$_instance;
 }