为yii2框架提供的简单导入模块
0.1.2
2021-06-29 14:38 UTC
Requires
- phpoffice/phpspreadsheet: ~1.2
- yiisoft/yii2: *
This package is auto-updated.
Last update: 2024-09-29 06:08:39 UTC
README
使用PHPOffice / PhpSpreadsheet更新的模块
Yii2-import是Yii框架的扩展。它可以帮助您将文件转换为模型。目前仅支持Excel格式。但很容易扩展以支持您的文件。
安装
您可以使用composer安装此扩展:
- 运行
$ php composer.phar require rikcage/yii2-import "*"
- 或在您的composer.json中添加
"rikcage/yii2-import": "*"
然后执行 'composer update'。
用法
假设有一个模型类
class Post extends Model { const STATUS_NEW = 0; const STATUS_APPROVED = 1; public $title; public $status; public $content; public static function getStatusList() { return [ self::STATUS_NEW = 'New', self::STATUS_APPROVED = 'Approved', ]; } }
以及以下表单和视图。
class ImportForm extends Model { public $file; public function rules() { return [ ['file', 'file', 'skipOnEmpty' => false, 'extensions' => 'xlsx'], ]; } }
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?> <?= $form->field($model, 'file')->fileInput() ?> <div class="form-group"> <?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?> </div> <?php ActiveForm::end(); ?>
用户上传了以下Excel文件。
现在您可以在控制器中使用以下代码来帮助您将文件转换为模型。
$uploadFile = UploadedFile::getInstance($model, 'file'); $importer = new Importer([ 'file' => $uploadFile, 'modelClass' => Post::className(), 'skipRowsCount' => 3, // description lines and header lines should be skipped 'columnMappings' => [ [ 'attribute' => 'title', 'required' => true, // if set this to true, the row that missing this value will be skipped. As in the example line 6 will be skipped ], [ 'attribute' => 'status', 'translation' => function($orgValue, $rowData) { return array_search($orgValue, Post::getStatusList()); }, // this function help fill the status like '0' instead of 'New' ] 'content', ], 'validateWhenImport' => true, //if set this attribute to true, importer will help you validate the models and report the validation errors by $importer->validationErrors ]); try { $posts = $importer->import(); } catch (InvalidFileException $e) { $model->addError('file', 'Invalid import file.'); }
现在您有了模型在 $posts 中。$posts 的结构将是
[ 4 => Post{title='Post 1', status=0, content='Content 1'}, 5 => Post{title='Post 2', status=1, content='Content 2'}, 7 => Post{title='Post 3', status=0, content='Content 4'}, ]
此外,您还可以通过 $importer->importRows 检查导入的行数,它是一个包含成功导入的行数的数组。
您可以如下通知用户导入结果。
Yii::$app->session->setFlash("success", count($importer->getImportRows()) . ' rows had been imported'); foreach ($importer->getValidationErrors() as $lineno => $errors) { foreach ($errors as $attribute => $errorMessages) { $error = $errorMessages[0]; break; } Yii::$app->session->addFlash("error", 'Line ' . $lineno . ' has error: ' . $error); }