PHPExcel 导出数据(xls或xlsx)- 助手类(函数)

本文链接:https://www.cnblogs.com/tujia/p/11358096.html

 

说明:简单好用的导出助手,轻松导出数据到 excel !!

 

使用示例:

Example:

ExcelHelper::export(['用户编号', '用户名'], [[1, '张三'], [2, '李四']], 'demo1.xls');

$bigTitle = 'This is Demo2';

$titles = [
    'userCode' => '用户编号',
    'userName' => '用户名'
];

$dataArray = [
    [
        'userCode' => 1,
        'age' => 18,
        'userName' => '张三'
    ],
    [
        'userCode' => 2,
        'age' => 22,
        'userName' => '李四'
    ]
];

ExcelHelper::export($titles, $dataArray, 'demo2.xlsx', $bigTitle);

 

源码:

php
namespace common\helpers;

/**
 * Excel 助手
 */
class ExcelHelper
{
    /**
     * 导出
     * @param  array    $titles         标题,一维数组,可传map或单纯标题
     * @param  array    $dataArray      数据,二维数组,可传map或单纯数据
     * @param  string   $filename       文件名,要带后缀
     * @param  string   $bigTitle       居中加粗的大标题,默认为空
     * @return file
     */
    public static function export(array $titles, array $dataArray, $filename, $bigTitle='')
    {
        // 后缀
        $suffix = substr($filename, strrpos($filename, '.'));
        empty($titles) && die('标题数组不能为空!');
        empty($dataArray) && die('数据数组不能为空!');
        !in_array($suffix, ['.xls', '.xlsx']) && die('文件名格式错误!');

        $oExcel = new \PHPExcel();
        $oExcel->setActiveSheetIndex(0);
        $sheet = $oExcel->getActiveSheet();
        
        // 行索引
        $rowIndex = $bigTitle!=''? 2:1;

        // 设置大标题
        if ($bigTitle != '') {
            $sheet->mergeCells('A1:'. chr(64+count($titles)) .'1');
            $sheet->getStyle('A1')->applyFromArray([
                'font' => ['bold'=>true],
                'alignment' => ['horizontal'=>\PHPExcel_Style_Alignment::HORIZONTAL_CENTER]
            ]);
            $sheet->setCellValue('A1', $bigTitle);
        }

        // 设置标题 A1 B1 C1 ....
        $colIndex = 0;
        $fieldsMap = [];
        foreach ($titles as $key => $title) {
            $fieldsMap[] = $key;
            $sheet->setCellValue(chr(65+$colIndex) . $rowIndex, $title);
            $colIndex++;
        }

        // 设置内容 A1 B1 C1 ....   A2 B2 C2 ....
        $rowIndex++;
        foreach ($dataArray as $key => $value)
        {
            foreach ($fieldsMap as $colIndex => $field) {
                $sheet->setCellValue(chr(65+$colIndex).$rowIndex, $value[$field]);
            }
            $rowIndex++;
        }

        if ($suffix == '.xlsx') {
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        } else {
            header('Content-Type: application/vnd.ms-excel');
        }
        header('Content-Disposition: attachment;filename="'. $filename .'"');
        $oWriter = \PHPExcel_IOFactory::createWriter($oExcel, 'Excel2007');
        $oWriter->save('php://output');
        $oExcel->disconnectWorksheets();
        exit;
    }
}

 

 原创内容,转载请声明出处!

本文链接:https://www.cnblogs.com/tujia/p/11358096.html

你可能感兴趣的:(PHPExcel 导出数据(xls或xlsx)- 助手类(函数))