PHPExcel 導出數據(xls或xlsx)- 助手類(函數)

本文連接:http://www.javashuo.com/article/p-yzorhflv-bq.htmlphp

 

說明:簡單好用的導出助手,輕鬆導出數據到 excel !!html

 

使用示例:數組

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);

 

源碼:app

<?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;
    }
}

 

 原創內容,轉載請聲明出處!spa

本文連接:http://www.javashuo.com/article/p-yzorhflv-bq.htmlexcel

相關文章
相關標籤/搜索