- 先通过composer下载一些插件
- 首先是PhpSpreadsheet
- https://github.com/PHPOffice/PhpSpreadsheet
- 和一个跟PhpSpreadsheet配合的插件
- composer require jianyan74/php-excel
- 下载慢或不能下载也可到Git下载
- https://github.com/jianyan74/php-excel
准备工作完成
导出
public function actionExport(){
$model = Staff::find()->asArray()->all();
$rules= [
['ID', 'id', 'text'],
['手机号码', 'mobile'], // 规则不填默认text
['昵称', 'fans.nickname', 'text'],
['关注/扫描', 'type', 'selectd', [1 => '关注', 2 => '扫描']],
['性别', 'sex', 'function', function($model){
return $model['sex'] == 1 ? '男' : '女';
}],
['创建时间', 'created_at', 'date', 'Y-m-d'],
];
return Excel::exportData($model, $rules, '测试', 'xls');
}
$model是我从数据中查出来的数据
$rules是我定义的一些规则
['ID', 'id', 'text'],//参数1为excel文件中显示的标题 参数2为数据库中的字段需一致 参数3为定义的类型不填默认text
导出就结束了
导入
<?php $form = ActiveForm::begin([
'action' => Url::to(['test/import']),
'options' =>['enctype'=>'multipart/form-data']
])?>
<input type="file" name="file">
<button type="submit" class="btn">导入数据</button>
<?php ActiveForm::end()?>
public function actionImport()
{
$file = $_FILES['file'];
$data = Excel::import($file['tmp_name'],2);// 参数1 文件的路径 参数2 从第几行开始取数据
foreach ($data as $k => $v){
$model = new Staff();
$model->name = $v[1];
$model->pwd = $v[2];
$model->user_name = $v[3];
$model->wage = $v[4];
$model->addTime = $v[5];
$model->save();
}
}
导入数据我使用的form表单,将xls文件上传到导入方法就行了。
至此,导入导出就全部结束了。
现在越来越多的插件被开发出来,使得我们的工作变得越来的轻松,也感谢他们的付出。