<?php
/**
 * @link      http://www.u-bo.com
 * @copyright 南京友博网络科技有限公司 
 * @license   http://www.u-bo.com/license/
 */

namespace common\models;

use Yii;
use PHPExcel;
use PHPExcel_IOFactory;
use PHPExcel_Style_Alignment;
use PHPExcel_Style_Border;

/**
 * Excel导出
 *
 * @author HuLimin <http://blog.u-bo.com>
 * @since 0.1
 */

class ExcelExport extends PHPExcel
{
    /**
     * 表头
     */
    public $excelTitle = NULL;

    /**
     * 文件名
     */
    public $fileTitle = NULL;

    /**
     * 列序以及其对应宽,表头,所在行,对应输出的属性
     *
     */
    public $cellArray = [
        'A' => [
            'width' => '15',
            'title' => '',
            'row' => 2,
            'attribute' => ''
        ]
    ];

    /**
     * 列的水平与垂直对齐方式，默认全部居中
     * 多列如A到D
     * 'A:D' => [
      'horizontal' => 'HORIZONTAL_CENTER',
      'vertical' => 'VERTICAL_CENTER'
      ]
     */
    public $styleAlignment = [
        'A' => [
            'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
            'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER
        ]
    ];

    /**
     * 需要合并的列表以及其名称
     * 如：A1->J1合并
     * ['A1:J1']
     */
    public $mergeCells = [];

    /*
     * 数据输出起始行，默认第三行
     */
    public $firstRow = 3;

    /*
     * 最后列名
     */
    public $lastRowName = 'A';

    /*
     * 需要导出的数据
     */
    public $exportData = [];

    /**
     * 其他信息
     */
    public $otherData = [];

    /**
     * 初始化
     */
    public function __construct()
    {
        /**
         * 文件名与表头名称在空的情况下默认为当前时间
         */
        if (empty($this->fileTitle)) {
            $this->fileTitle = date('YmdHis');
        }
        $this->excelTitle = iconv("UTF-8", "GB2312", $this->excelTitle); //转义，避免乱码
        $this->fileTitle = iconv("UTF-8", "GB2312", $this->fileTitle); //转义，避免乱码
    }

    /**
     * 导出
     */
    public function export()
    {
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $this->fileTitle . '.xls"');
        header('Cache-Control: max-age=0');

        $objPHPExcel = new PHPExcel();
        $objPHPExcel->setActiveSheetIndex(0);
        $objActSheet = $objPHPExcel->getActiveSheet();

        // Set document properties
        $objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
            ->setLastModifiedBy("Maarten Balliauw")
            ->setTitle("Office 2007 XLSX Test Document")
            ->setSubject("Office 2007 XLSX Test Document")
            ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
            ->setKeywords("office 2007 openxml php")
            ->setCategory("Test result file");

        $styleArray = [
            'borders' => [
                'allborders' => [
                    'style' => PHPExcel_Style_Border::BORDER_THIN,
                    'color' => ['argb' => 'FF000000'],
                ]
            ],
        ];
        $styleArray1 = [
            'font' => [
                'bold' => true,
                'color' => ['argb' => '00000000'],
            ],
            'alignment' => [
                'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
            ],
        ];
       
        //对齐方式处理
        foreach ($this->styleAlignment as $s => $sVo) {
            $objActSheet->getStyle($s)->getAlignment()->setHorizontal($sVo['horizontal'])->setVertical($sVo['vertical']);
        }

        //合并单元格
        if (!empty($this->mergeCells)) {
            foreach ($this->mergeCells as $m => $mVo) {
                $objActSheet->mergeCells($mVo);
            }
        }
        $objActSheet->setCellValue('A1', $this->excelTitle);
        //表头处理，以及宽度处理
        foreach ($this->cellArray as $c => $cVo) {
            $objPHPExcel->getActiveSheet()->getColumnDimension($c)->setWidth($cVo['width']);
            $objActSheet->setCellValue($c . $cVo['row'], $cVo['title']);
            $objPHPExcel->getActiveSheet()->getStyle($c . $cVo['row'])->applyFromArray($styleArray1);
            $this->lastRowName = $c;
        }

        $row = (int) $this->firstRow;
        //数据输出
        foreach ($this->exportData as $key => $value) {
            foreach ($this->cellArray as $c => $cVo) {
                $objActSheet->setCellValue($c . $row, $value[$cVo['attribute']]);
            }
            $row = $row + 1;
        }

        $objPHPExcel->getActiveSheet()->getStyle('A1:' . $this->lastRowName . $row)->applyFromArray($styleArray); //表格边框线
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
    }
}