Ипорт из Excel

Общие вопросы по использованию фреймворка. Если не знаете как что-то сделать и это про Yii, вам сюда.
Ответить
Viktor
Сообщения: 116
Зарегистрирован: 2014.03.10, 14:06

Ипорт из Excel

Сообщение Viktor »

Всем привет :) . Мне нужно проводить импорт из Excel в базу данных. Подскажите пожалуйста расширение для Yii, возможно кто раньше уже делал такое. Помогите плиз :)
Аватара пользователя
Altenrion
Сообщения: 44
Зарегистрирован: 2013.03.18, 12:05
Контактная информация:

Re: Ипорт из Excel

Сообщение Altenrion »

Посмотри обсуждение на тостере на эту же тему : https://toster.ru/q/42664

Сам реализовывал аплоап с помощью PhpExcel но он не оформлялся в экстеншен для yii вроде. Да и люди пишут что он устарел сильно.
Viktor
Сообщения: 116
Зарегистрирован: 2014.03.10, 14:06

Re: Ипорт из Excel

Сообщение Viktor »

;) спасибо за направление) сейчас все попробую. пробовал JPhpExcelReader, что то не очень получаеться
Viktor
Сообщения: 116
Зарегистрирован: 2014.03.10, 14:06

Re: Ипорт из Excel

Сообщение Viktor »

сейчас новая проблема, мне нужно сохранять сущности в бд, я делаю так:

Код: Выделить всё

    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>";
    } 
но получаю только пустые строки в таблице. что я делаю неправильно? :)
Аватара пользователя
Altenrion
Сообщения: 44
Зарегистрирован: 2013.03.18, 12:05
Контактная информация:

Re: Ипорт из Excel

Сообщение Altenrion »

думаю проблема кроется тут :

Код: Выделить всё

              $model = new Members;
              $model->attributes = $column;
              $model->save();
Для такого присвоения , атрибуты модели должны иметь специфичный вид. Например "modelName['name']" , "modelName['age']"...

В вашем случае я бы прописал вместо этих трех строк следующее:

Код: Выделить всё

            var_dump($row);
            Yii::app()->end();
 
Будет на экране полезная инфа...
Viktor
Сообщения: 116
Зарегистрирован: 2014.03.10, 14:06

Re: Ипорт из Excel

Сообщение Viktor »

я уже смотрел, я получаю массивы строк. Например:

Код: Выделить всё

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)
 
Первый массив лейблов.
Аватара пользователя
Altenrion
Сообщения: 44
Зарегистрирован: 2013.03.18, 12:05
Контактная информация:

Re: Ипорт из Excel

Сообщение Altenrion »

Покажите код модели Members
Viktor
Сообщения: 116
Зарегистрирован: 2014.03.10, 14:06

Re: Ипорт из Excel

Сообщение Viktor »

Код: Выделить всё

<?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);
    }
}
 
Аватара пользователя
Altenrion
Сообщения: 44
Зарегистрирован: 2013.03.18, 12:05
Контактная информация:

Re: Ипорт из Excel

Сообщение Altenrion »

Первое : с закоменченным массивом Rules модель не сохранится, так как у вас все поля являются usafe, вы оставили лишь последнюю строку рабочей, но там поля safe только для поиска.
Второе: в вашем случае скорее всего нужно будет в ручную присвоить столбцы excel к атрибутам модели. Например :

Код: Выделить всё

    foreach ($row as $key => $column) {
        $model->surname_ru = $row['C'];
        $model->name_ru = $row['D'];
    }
 
Viktor
Сообщения: 116
Зарегистрирован: 2014.03.10, 14:06

Re: Ипорт из Excel

Сообщение Viktor »

спасибо сейчас попробую)
Аватара пользователя
Altenrion
Сообщения: 44
Зарегистрирован: 2013.03.18, 12:05
Контактная информация:

Re: Ипорт из Excel

Сообщение Altenrion »

Главное, что бы помогло)
Viktor
Сообщения: 116
Зарегистрирован: 2014.03.10, 14:06

Re: Ипорт из Excel

Сообщение Viktor »

вручную сохраняет спасибо) но проблема в том что каждую запись сохраняет по 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
Viktor
Сообщения: 116
Зарегистрирован: 2014.03.10, 14:06

Re: Ипорт из Excel

Сообщение Viktor »

все вопрос решен. спасибо тебе огромное помог очень сильно:)
Аватара пользователя
Altenrion
Сообщения: 44
Зарегистрирован: 2013.03.18, 12:05
Контактная информация:

Re: Ипорт из Excel

Сообщение Altenrion »

Незачто)) Помогая друг другу, мы помогаем комьюнити в целом ))

п.с.: обращайтесь )
Ответить