Экспорт атрибутов модели в Excel файл

Обсуждение документации. Переводы Cookbook и авторские рецепты.
Ответить
Mike
Сообщения: 5
Зарегистрирован: 2013.09.04, 21:04

Экспорт атрибутов модели в Excel файл

Сообщение Mike »

Всем привет! Появилась задумка экспорта выборочных полей модели в *.xls файл, и вот решил написать behavior, который подключается к модели CActiveRecord и расширяет ее функционал по поводу экспорта полей.
Что для этого Вам нужно сделать:
В Модели:
1) Подключить поведение.
2) Написать метод public fieldsExportExl(), в нём указываются выборочный массив полей для экспорта.
3) В Модели должен быть метод search().
В Контроллере можно вызывать экспорт, по нажатию кнопки экспорта.

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

if (isset($_POST['export']) && $_POST['export'] == 1){
    $model->attributes = $_POST[$class];
    // export to xls format.
    $model->excel_export->export();
}
Вот и само поведение с примером методов:

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

<?php
/**
 * Export fields model to excel format.
 * For export is used method model search().
 * In the method can be used to check the current scenario "ExcelExport".
 *
 * @author Mike
 * @version 1.0
 * @since version - 12.09.2013
 * @example
 *
 * CActiveRecord:
 *
 * public function behaviors(){
        return array(
            'excel_export'=>array(
                'class'=>'ExcelExportBehavior',
                'name_file'=>'List_users_'.date('Y-m-d')
            )
        );
    }

    public function search(){
        $criteria=new CDbCriteria;
        $criteria->compare('id',$this->id);
        $criteria->compare('code',$this->code, true);
        $criteria->compare('document_code',$this->document_code, true);
        $criteria->compare('gender',$this->gender);
        $criteria->compare('date_create',$this->date_create, true);
        $criteria->compare('info',$this->info, true);

        if ($this->getScenario() == 'ExcelExport'){
            return new CActiveDataProvider(get_class($this), array(
                'criteria'=>$criteria,
                'pagination'=>false,
            ));
        }else{
            return new CActiveDataProvider(get_class($this), array(
                'criteria'=>$criteria,
                'pagination'=>array(
                    'pageSize'=>50,
                ),
            ));
        }
    }

    //The fields for export list to Excel.
    public function fieldsExportExl(){
        return array(
            'code'=>null,
            'document_code'=>null,
            'fln'=>$this->getFLN(),
            'gender'=>Lookup::item_translated('Gender', $this->gender),
        );
    }

    // CController:
    public function actionName(){
        // The executing Export to Excel format
        $model->excel_export->export();
    }
 */
class ExcelExportBehavior extends CBehavior{
    /**
     * The name excel file.
     */
    public $name_file = '';
    /**
     * Export model fields to *.xls format.
     */
    public function export(){
        if ($this->name_file == ""){
            // the name file by default
            $this->name_file = date('Y-m-d');
        }
        // the setting current scenario
        $this->getOwner()->setScenario('ExcelExport');

        Yii::import('ext.excell.Excell');
        $exc = new Excell();
        $ws = &$exc->addWorksheet();
        $format = &$exc->addFormat();
        $format->setNumFormat('@');
        $format->setBold();
        // set names columns
        $attr_labels = $this->getOwner()->attributeLabels();
        // the number of fields for export to excel
        $cnf = 0;
        // get fields for export to xls file
        if (method_exists($this->getOwner(), 'fieldsExportExl')){
            $fds_exprt = $this->getOwner()->fieldsExportExl();
            if (!is_array($fds_exprt)){
                throw new CHttpException(501, 'Model method returns an incorrect result.');
            }
            if (($cnf = count($fds_exprt)) == 0){
                throw new CHttpException(501, 'The fields for export is not not specified.');
            }
        }else{
            throw new CHttpException(501, 'Model method of fieldsExportExl() is not found.');
        }
        // receiving names fields
        $name_fields = array();
        foreach($fds_exprt as $k=>$f){
            $name_fields[] = $k;
        }
        for($i = 0; $i < $cnf; $i++){
            $ws->write(0, $i, iconv('utf-8','cp1251//IGNORE', $attr_labels[$name_fields[$i]]), $format);
            $ws->setColumn($i, $i, strlen($attr_labels[$name_fields[$i]]));
        }
        $format = &$exc->addFormat();
        $format->setNumFormat('@');
        $row_num = 1;
        if (!method_exists($this->getOwner(), 'search')){
            throw new CHttpException(501, 'Model method of search() is not found.');
        }
        $data = $this->getOwner()->search();
        // rows
        foreach($data->data as $r){
            // data records
            $dr = $r->fieldsExportExl();
            // columns
            for($i = 0; $i < $cnf; $i++){
                // value field
                $vf = $dr[$name_fields[$i]];
                $ws->write($row_num, $i, iconv('utf-8','cp1251//IGNORE', $vf !== null ? $vf : $r->{$name_fields[$i]}), $format);
            }
            $row_num++;
        }
        $exc->send($this->name_file.'.xls');
        $exc->close();
    }
}
?>
Ответить