lucasguo/yii2-import

yii2 框架的简单导入模块

安装次数: 4,700

依赖者: 0

建议者: 0

安全: 0

星标: 2

关注者: 2

分支: 5

开放问题: 0

类型:yii2-extension

0.1.1 2016-12-06 07:58 UTC

This package is not auto-updated.

Last update: 2024-09-14 19:53:14 UTC


README

Yii2-import 是 Yii 框架的一个扩展。它可以帮助您将文件导入模型中。目前仅支持 Excel 格式。但很容易扩展以支持您的文件。

安装

您可以使用 composer 安装此扩展,通过

  • 运行
$ php composer.phar require lucasguo/yii2-import "*"
  • 或在您的 composer.json 中添加
"lucasguo/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);
}