我的表单中有两个按钮。一个是' export'按钮和另一个是'创建' button.While保存表单我必须上传excel文件。这个excel文件包含5行的单行。点击导出按钮我必须从excel获取所有值并在我的表单中设置这些值。最后点击创建按钮我必须将这些值保存在数据库中。 在这里我的问题是我无法验证excel文件并从excel获取值以在我的表单中设置数据。
我的表单代码是:
<?php $form = ActiveForm::begin([
'id' => 'memform',
'options' => ['class' => 'form-horizontal',['enctype' => 'multipart/form-data'],],
'fieldConfig' => [
'template' => "{label}\n<div class=\"col-lg-6\">{input}</div>\n<div class=\"col-lg-12\">{error}</div>",
'labelOptions' => ['class' => 'col-lg-6 control-label'],
],
]); ?>
<?= $form->field($model, 'file')->fileInput(); ?>
<?= Html::a('export', ['import-excel','model' => $model], ['class' => 'btn btn-success','style' => 'float:left;width: 200px; border-radius: 5px;']) ?>
<h3 class="box-title">General Info:</h3> </div>
<div class="col-md-4">
<?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
</div>
<div class="col-md-4">
<?= $form->field($model, 'date')->textInput(['maxlength' => true]) ?>
</div>
<div class="col-md-4">
<?= $form->field($model, 'regd_dt')->textInput(['maxlength' => true]) ?>
</div>
<div class="col-sm-4">
<?= $form->field($model, 'estd_type')->dropDownList(
ArrayHelper::map(CodeValue::getEstdType(),'cv_id','cv_lbl'),
['prompt'=>'Select est Type']
)
?>
</div>
<div class="col-sm-4">
<?= $form->field($model, 'org_type')->dropDownList(
ArrayHelper::map(CodeValue::getOrgType(),'cv_id','cv_lbl'),
['prompt'=>'Select Org Type']
)
?>
</div>
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
<?php ActiveForm::end(); ?>
我的控制器是:
public function actionCreate()
{
$model = new GeneralInfo();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['index', 'id' => $model->sfcl_id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
public function actionImportExcel(){
$model = new GeneralInfo();
$model->file = UploadedFile::getInstance($model, 'file');
$file = $model->file->tempName;
if (isset(model->file)) {
try{
$inputFileType=\PHPExcel_IOFactory::Identify($file);
$objReader=\PHPExcel_IOFactory::CreateReader($inputFileType);
$objPHPExcel=$objReader->load($file);
}
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,False);
if($row==1){
continue;
}
$sfcl=new GeneralInfo();
$sfcl->name=$rowData[0][0];
echo $sfcl->name;die;
}
}
else {
return $this->render('_form', [
'model' => $model,
]);
}
}
我的模型是这样的:
public function rules()
{
return [
['file', 'required'],
['name','estd_dt', 'regd_dt', 'type', 'org_type'], 'required'],
[['type', 'org_type', 'crtd_by', 'updt_by', 'updt_cnt'], 'integer'],
[['name','estd_dt', 'regd_dt'], 'string', 'max' => 50],
[['file'], 'file', 'extensions' => 'xls, xlsx', 'maxSize'=>1024*1024*20],
];
}