TP5 PhpExcel 单sheet利用fromArray一次性导出数据

$arr[] = [ '课程标题', '正式课/试听课', '课时数量', '课程总价(元)'];

        if (!empty($data)) {
            foreach ($data as $k => $v) {
                $course_type = $v['course_type'] == 1 ? '正式课' : '试听课';
                //按照数据对应把数据循环放进$arr数组
                $arr[] = [ $v['title'], $course_type, $v['course_hour'],$v['total_price']];
            }
        }

        vendor('phpexcel.PHPExcel');
        $objPHPExcel = new \PHPExcel();                //实例化一个PHPExcel()对象
        $objSheet = $objPHPExcel->getActiveSheet();   //选取当前的sheet对象
        $objSheet->setTitle('sheet1');              //对当前sheet对象命名名称

        $objSheet->fromArray($data); //利用fromArray()直接一次性填充数据
        vendor('phpexcel.PHPExcel.IOFactory');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007'); //设定写入excel的类型
        $path = UPLOAD_PATH . 'excel/课程.xlsx';
        $objWriter->save($path); //保存文件
        return $path;

一些常用设置

//所有单元格文字居中
$objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
//所有单元格文字垂直居中
$objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
//所有单元格(行)默认高度
$objPHPExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(20);
//所有单元格(列)默认宽度
$objPHPExcel->getActiveSheet()->getDefaultColumnDimension()->setWidth(20);
//设置行高度
$objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(30);
//设置列宽度
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(30);
//设置文字大小
$objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(18);
//设置是否加粗
$objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
// 设置文字颜色
$objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->getColor()->setARGB(PHPExcel_Style_Color::COLOR_WHITE);
//设置文字居左(HORIZONTAL_LEFT,默认值)中(HORIZONTAL_CENTER)右(HORIZONTAL_RIGHT)
$objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
//垂直居中
$objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
//设置填充颜色
$objPHPExcel->getActiveSheet()->getStyle('A1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
//设置填充颜色 
$objPHPExcel->getActiveSheet()->getStyle('A1')->getFill()->getStartColor()->setRGB('ff7f24');

你可能感兴趣的:(TP5 PhpExcel 单sheet利用fromArray一次性导出数据)