<?php


namespace App\Http\helper;


class PHPExcel
{
    /**
     * 垂直excel
     * @param string $name excel名
     * @param array $title 标题
     * @param array $data 数据
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \PHPExcel_Writer_Exception
     */
    public static function downExcel($name, $title, $data)
    {
        // 创建对象
        $objPHPExcel = new \Maatwebsite\Excel\Classes\PHPExcel();

        // 显示错误信息
        error_reporting(E_ALL);

        $count = count($data);

        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);

        for ($i = 0; $i < $count; $i++) {

            $objPHPExcel->getActiveSheet()->getStyle('A' . ($i + 1))->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A' . ($i + 1), $title[$i]);

        }

        for ($i = 0; $i < $count; $i++) {
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B' . ($i + 1), $data[$i]);
        }

        // Rename sheet
        $objPHPExcel->getActiveSheet()->setTitle($name);

        // Set active sheet index to the first sheet, so Excel opens this as the first sheet
        $objPHPExcel->setActiveSheetIndex(0);

        // 设置输出
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename=' . $name . '.xls');
        header('Cache-Control: max-age=0');

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }
}
