mysql - Import Excel in Yii2 -
i have yii2 application using advanced template , database mysql, make function import excel file 1 of table, made function in controller named student contains crud of students data.this code
public function actionimportexcel() { $inputfile = 'uploads/siswa_file.xlsx'; try{ $inputfiletype = \phpexcel_iofactory::identify($inputfile); $objreader = \phpexcel_iofactory::createreader($inputfiletype); $objphpexcel = $objreader->load($inputfile); } catch (exception $e) { die('error'); } $sheet = $objphpexcel->getsheet(0); $highestrow = $sheet->gethighestrow(); $highestcolumn = $sheet->gethighestcolumn(); for($row=1; $row <= $highestrow; $row++) { $rowdata = $sheet->rangetoarray('a'.$row.':'.$highestcolumn.$row,null,true,false); if($row==1) { continue; } $siswa = new siswa(); $siswa->nis = $rowdata[0][0]; $siswa->nama_siswa = $rowdata[0][1]; $siswa->jenis_kelamin = $rowdata[0][2]; $siswa->ttl = $rowdata[0][3]; $siswa->alamat = $rowdata[0][4]; $siswa->telp = $rowdata[0][5]; $siswa->agama = $rowdata[0][6]; $siswa->nama_ortu = $rowdata[0][7]; $siswa->telp_ortu = $rowdata[0][8]; $siswa->pekerjaan_ortu = $rowdata[0][9]; $siswa->tahun_masuk = $rowdata[0][10]; $siswa->kelas = $rowdata[0][11]; $siswa->save(); print_r($siswa->geterrors()); } die('okay'); } but don't know how make button in view make function work. mean want make button when user click button , browse excel file can import file , data inside excel can import database
first should upload file
and processing function
there several parts of code must produce ..
eg view user upload file
view: @app/views/site/upload.php
<?php $form = activeform::begin(['options' => ['enctype' => 'multipart/form-data']]) ?> <?= $form->errorsummary($model); ?> <?= $form->field($model, 'imagefile')->fileinput() ?> <button>submit</button> <?php activeform::end() ?>controller: @app/controllers/sitecontroller.php
namespace app\controllers; use yii; use yii\web\controller; use app\models\uploadform; use yii\web\uploadedfile; class sitecontroller extends controller { public function actionupload() { $model = new uploadform(); if (yii::$app->request->ispost) { $model->imagefile = uploadedfile::getinstance($model, 'imagefile'); if ($model->upload()) { // file uploaded return; } } return $this->render('upload', ['model' => $model]); } }model: @app/models/uploadform.php
namespace app\models; use yii\base\model; use yii\web\uploadedfile; class uploadform extends model { /** * @var uploadedfile */ public $imagefile; public function rules() { return [ [['imagefile'], 'file', 'skiponempty' => false, 'extensions' => 'png, jpg'], ]; } public function upload() { if ($this->validate()) { $this->imagefile->saveas('uploads/' . $this->imagefile->basename . '.' . $this->imagefile->extension); return true; } else { return false; } } }
the code this doc
Comments
Post a Comment