gevman / yii2-excel-import
将Excel表格导出到ActiveRecord模型
1.0.0
2018-03-16 22:40 UTC
Requires
- phpoffice/phpspreadsheet: ^1.2
- yiisoft/yii2: ~2.0.14
This package is auto-updated.
Last update: 2024-09-22 16:11:40 UTC
README
将Excel导入ActiveRecord模型
安装
使用Composer
composer require gevman/yii2-excel-import
方法
__constructor
支持以下属性的数组参数
filePath
- 要导入的Excel文件的完整路径activeRecord
- 应保存导入数据的ActiveRecord类名scenario
- ActiveRecord场景,如果留空则不设置场景skipFirstRow
- 如果为true,将跳过Excel的第一行(例如,标题行),否则将尝试保存第一行fields[]
- 字段定义数组
fields[]
attribute
- 来自您的ActiveRecord类的属性名value
- 如果传递了可调用的,它将接收当前行,并将返回的值保存到AR中;否则,它将在当前行中查找键值传递的值的元素
验证
验证每个填充的AR模型,如果有任何错误则返回false,否则返回true
保存
保存填充的AR模型,如果模型尚未验证,则返回每个保存的AR模型的主键数组;否则,在保存之前将验证所有模型
getErrors
将返回按行索引索引的AR模型错误数组
getModels
将返回填充的AR模型数组
示例
- 定义字段
$uploadedFile = \yii\web\UploadedFile::getInstanceByName('file'); $importer = new \Gevman\Yii2Excel\Importer([ 'filePath' => $uploadedFile->tempName, 'activeRecord' => Product::class, 'scenario' => Product::SCENARIO_IMPORT, 'skipFirstRow' => true, 'fields' => [ [ 'attribute' => 'keywords', 'value' => 1, ], [ 'attribute' => 'itemTitle', 'value' => 2, ], [ 'attribute' => 'marketplaceTitle', 'value' => 3, ], [ 'attribute' => 'brand', 'value' => function ($row) { return strval($row[4]); }, ], [ 'attribute' => 'category', 'value' => function ($row) { return strval($row[4]); }, ], [ 'attribute' => 'mpn', 'value' => function ($row) { return strval($row[6]); }, ], [ 'attribute' => 'ean', 'value' => function ($row) { return strval($row[7]); }, ], [ 'attribute' => 'targetPrice', 'value' => 8, ], [ 'attribute' => 'photos', 'value' => function ($row) { $photos = []; foreach (StringHelper::explode(strval($row[11]), ',', true, true) as $photo) { if (filter_var($photo, FILTER_VALIDATE_URL)) { $file = @file_get_contents($photo); if ($file) { $filename = md5($file) . '.jpg'; file_put_contents(Yii::getAlias("@webroot/gallery/$filename"), $file); $photos[] = $filename; } } else { $photos[] = $photo; } } return implode(',', $photos); } ], [ 'attribute' => 'currency', 'value' => 13, ], ], ]);
- 验证、保存并显示错误
if (!$importer->validate()) { foreach($importer->getErrors() as $rowNumber => $errors) { echo "$rowNumber errors <br>" . implode('<br>', $errors); } } else { $importer->save(); }
仅
$importer->save(); foreach($importer->getErrors() as $rowNumber => $errors) { echo "$rowNumber errors <br>" . implode('<br>', $errors); }