xpbl4 / yii2-import
Yii2框架导入Excel数据的扩展
v1.0.0
2023-08-29 03:59 UTC
Requires
This package is auto-updated.
Last update: 2024-09-30 02:02:53 UTC
README
为Yii2框架提供使用PhpSpreadsheet导入数据的扩展。
安装
安装此扩展的首选方式是通过 composer。
运行以下命令之一
php composer.phar require --prefer-dist xpbl4/yii2-import "*"
或者在您的 composer.json
文件的 require 部分添加
"xpbl4/yii2-import": "*"
。
使用方法
实现 ImportInterface
class Contact extends \yii\db\ActiveRecord implements ImportInterface
{
...
public function import($reader, $row, $data)
{
if ($row == 0) {
if ($data != ['First Name', 'Last Name', 'Email']) {
$reader->addError($row, 'Invalid headers.');
return false;
}
// Skip header row
return true;
}
// Create contact from data
$contact = new Contact;
...
}
}
现在您可以使用 ExcelReader
和您的类作为 model
来导入数据
public function actionImport()
{
$form = new ImportForm();
$form->file = UploadedFile::getInstanceByName('file');
if ($form->validate()) {
Contact::deleteAll();
$reader = new ExcelReader(['model' => Contact::className()]);
$reader->import($form->file->tempName);
if ($reader->getErrors()) {
// Handle errors
...
}
}
return $form;
}