Ипорт из Excel
Ипорт из Excel
Всем привет . Мне нужно проводить импорт из Excel в базу данных. Подскажите пожалуйста расширение для Yii, возможно кто раньше уже делал такое. Помогите плиз
Re: Ипорт из Excel
Посмотри обсуждение на тостере на эту же тему : https://toster.ru/q/42664
Сам реализовывал аплоап с помощью PhpExcel но он не оформлялся в экстеншен для yii вроде. Да и люди пишут что он устарел сильно.
Сам реализовывал аплоап с помощью PhpExcel но он не оформлялся в экстеншен для yii вроде. Да и люди пишут что он устарел сильно.
Re: Ипорт из Excel
спасибо за направление) сейчас все попробую. пробовал JPhpExcelReader, что то не очень получаеться
Re: Ипорт из Excel
сейчас новая проблема, мне нужно сохранять сущности в бд, я делаю так:
но получаю только пустые строки в таблице. что я делаю неправильно?
Код: Выделить всё
public function actionUploadExcel()
{
$sheet_array = Yii::app()->yexcel->readActiveSheet(Yii::getPathOfAlias('webroot') . '/excel/users.xls');
echo "<table>";
foreach ($sheet_array as $row) {
echo "<tr>";
foreach ($row as $key => $column) {
$model = new Members;
$model->attributes = $column;
$model->save();
echo "<td>$column</td>";
}
echo "</tr>";
}
echo "</table>";
}
Re: Ипорт из Excel
думаю проблема кроется тут :
Для такого присвоения , атрибуты модели должны иметь специфичный вид. Например "modelName['name']" , "modelName['age']"...
В вашем случае я бы прописал вместо этих трех строк следующее:
Будет на экране полезная инфа...
Код: Выделить всё
$model = new Members;
$model->attributes = $column;
$model->save();
В вашем случае я бы прописал вместо этих трех строк следующее:
Код: Выделить всё
var_dump($row);
Yii::app()->end();
Re: Ипорт из Excel
я уже смотрел, я получаю массивы строк. Например:
Первый массив лейблов.
Код: Выделить всё
array (size=12)
'A' => string 'Номер внутренний' (length=31)
'B' => string 'Data' (length=4)
'C' => string 'Фамилия участника рус' (length=40)
'D' => string 'Имя участника рус' (length=32)
'E' => string 'Должность ' (length=19)
'F' => string 'Surname' (length=7)
'G' => string 'Name' (length=4)
'H' => string 'Position' (length=8)
'I' => string 'Название компании / Company Name' (length=48)
'J' => string 'e-mail' (length=6)
'K' => string 'Статус/ status' (length=20)
'L' => string 'Цвет оплаты' (length=21)
Re: Ипорт из Excel
Покажите код модели Members
Re: Ипорт из Excel
Код: Выделить всё
<?php
/**
* This is the model class for table "{{members}}".
*
* The followings are the available columns in table '{{members}}':
* @property string $id
* @property string $surname_ru
* @property string $name_ru
* @property string $position_ru
* @property string $telephone
* @property string $company_name_ru
* @property string $law_company_name
* @property string $sphere_comp_act
* @property string $surname_en
* @property string $name_en
* @property string $position_en
* @property string $company_name_en
* @property string $table_number
* @property integer $status
* @property string $password
* @property string $email
*/
class Members extends CActiveRecord
{
/**
* @return string the associated database table name
*/
public function tableName()
{
return '{{members}}';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
// array('status', 'numerical', 'integerOnly' => true),
// array('surname_ru, name_ru, position_ru, telephone, company_name_ru, law_company_name, sphere_comp_act, surname_en, name_en, position_en, company_name_en, table_number, password', 'length', 'max' => 255),
// array('email', 'length', 'max' => 20),
// The following rule is used by search().
// @todo Please remove those attributes that should not be searched.
array('id, surname_ru, name_ru, position_ru, telephone, company_name_ru, law_company_name, sphere_comp_act, surname_en, name_en, position_en, company_name_en, table_number, status, password, email', 'safe'),
);
}
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array();
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'Идентификатор',
'surname_ru' => 'Фамилия участника',
'name_ru' => 'Имя участника',
'position_ru' => 'Должность',
'telephone' => 'Личный телефон (мобильный)',
'company_name_ru' => 'Название компании',
'law_company_name' => 'Юридическое название компании',
'sphere_comp_act' => 'Сфера деятельности компании',
'surname_en' => 'Surname',
'name_en' => 'Name',
'position_en' => 'Position',
'company_name_en' => 'Company Name',
'table_number' => 'Номер стола',
'status' => 'Статус',
'password' => 'Пароль пользователя',
'email' => 'Почта',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
*
* Typical usecase:
* - Initialize the model fields with values from filter form.
* - Execute this method to get CActiveDataProvider instance which will filter
* models according to data in model fields.
* - Pass data provider to CGridView, CListView or any similar widget.
*
* @return CActiveDataProvider the data provider that can return the models
* based on the search/filter conditions.
*/
public function search()
{
// @todo Please modify the following code to remove attributes that should not be searched.
$criteria = new CDbCriteria;
$criteria->compare('id', $this->id, true);
$criteria->compare('surname_ru', $this->surname_ru, true);
$criteria->compare('name_ru', $this->name_ru, true);
$criteria->compare('position_ru', $this->position_ru, true);
$criteria->compare('telephone', $this->telephone, true);
$criteria->compare('company_name_ru', $this->company_name_ru, true);
$criteria->compare('law_company_name', $this->law_company_name, true);
$criteria->compare('sphere_comp_act', $this->sphere_comp_act, true);
$criteria->compare('surname_en', $this->surname_en, true);
$criteria->compare('name_en', $this->name_en, true);
$criteria->compare('position_en', $this->position_en, true);
$criteria->compare('company_name_en', $this->company_name_en, true);
$criteria->compare('table_number', $this->table_number, true);
$criteria->compare('status', $this->status);
$criteria->compare('password', $this->password, true);
$criteria->compare('email', $this->email, true);
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
));
}
/**
* Returns the static model of the specified AR class.
* Please note that you should have this exact method in all your CActiveRecord descendants!
* @param string $className active record class name.
* @return Members the static model class
*/
public static function model($className = __CLASS__)
{
return parent::model($className);
}
}
Re: Ипорт из Excel
Первое : с закоменченным массивом Rules модель не сохранится, так как у вас все поля являются usafe, вы оставили лишь последнюю строку рабочей, но там поля safe только для поиска.
Второе: в вашем случае скорее всего нужно будет в ручную присвоить столбцы excel к атрибутам модели. Например :
Второе: в вашем случае скорее всего нужно будет в ручную присвоить столбцы excel к атрибутам модели. Например :
Код: Выделить всё
foreach ($row as $key => $column) {
$model->surname_ru = $row['C'];
$model->name_ru = $row['D'];
}
Re: Ипорт из Excel
спасибо сейчас попробую)
Re: Ипорт из Excel
Главное, что бы помогло)
Re: Ипорт из Excel
вручную сохраняет спасибо) но проблема в том что каждую запись сохраняет по 12 раз, возможно собака в array (size=12):
Код: Выделить всё
array (size=12)
'A' => float 1
'B' => null
'C' => string 'Аверьянова' (length=20)
'D' => string 'Наталия' (length=14)
'E' => null
'F' => string 'Homeland Group' (length=14)
'G' => null
'H' => null
'I' => null
'J' => null
'K' => string 'оплачено' (length=16)
'L' => float 1
Re: Ипорт из Excel
все вопрос решен. спасибо тебе огромное помог очень сильно:)
Re: Ипорт из Excel
Незачто)) Помогая друг другу, мы помогаем комьюнити в целом ))
п.с.: обращайтесь )
п.с.: обращайтесь )