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


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

 

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

 

使用示例1:

 

使用示例2:

 支持數字格式請看:phpoffice\phpexcel\Classes\PHPExcel\Style\NumberFormat.php

 

使用示例3:

 

源碼:

<?php
namespace common\helpers;

use yii\helpers\ArrayHelper;

/**
 * Excel 助手
 */
class ExcelHelper
{
    public static $styleFormat = [];

    /**
     * @see \PHPExcel_Style_NumberFormat
     */
    public static function setStyleFormat($format)
    {
        self::$styleFormat = $format;
    }

    /**
     * 導出
     * @see    https://www.cnblogs.com/tujia/p/11358096.html
     * @param  array    $titles         標題,一維數組,可傳map或單純標題
     * @param  array    $dataArray      數據,二維數組,可傳map或單純數據
     * @param  string   $filename       文件名,要帶后綴
     * @param  string   $bigTitle       居中加粗的大標題,默認為空
     * @param  array    $extra          擴展數據
     * @return file
     */
    public static function export(array $titles, $dataArray, $filename, $bigTitle='', $extra=[])
    {
        set_time_limit(0);
        ini_set('memory_limit', '512M');

        // 后綴
        $suffix = substr($filename, strrpos($filename, '.'));
        empty($titles) && die('標題數組不能為空!');
        empty($dataArray) && die('數據數組不能為空!');
        !in_array($suffix, ['.xls', '.xlsx']) && die('文件名格式錯誤!');

        $cacheMethod = \PHPExcel_CachedObjectStorageFactory::cache_in_memory_serialized;
        $cacheSettings = array('memoryCacheSize ' => '512MB');
        \PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);

        $oExcel = new \PHPExcel();
        $oExcel->setActiveSheetIndex(0);
        $sheet = $oExcel->getActiveSheet();

        // 設置列數據格式
        if (!empty(self::$styleFormat)) {
            $fields = array_keys($titles);
            foreach (self::$styleFormat as $field => $formatCode) {
                $offset = array_search($field, $fields);
                $col = chr(65+$offset);
                $sheet->getStyle($col)->getNumberFormat()->setFormatCode($formatCode);
            }
        }

        // 行索引
        $rowIndex = $bigTitle!=''? 2:1;

        $chr = [
            'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
            'AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ'
        ];

        // 設置大標題
        if ($bigTitle != '') {
            $sheet->mergeCells('A1:'. $chr[count($titles)-1] .'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[$colIndex] . $rowIndex, $title);
            $colIndex++;
        }

        // 設置內容 A1 B1 C1 ....   A2 B2 C2 ....
        $rowIndex++;
        foreach ($dataArray as $key => $value)
        {
            foreach ($fieldsMap as $colIndex => $field) {
                if (strrpos($field, '|') !== false) {
                    $temp1 = explode('|', $field);
                    $pos = strrpos($temp1[1], '.');
                    $pos === false && $pos = strlen($temp1[1]);
                    $temp2 = [];
                    $temp2[0] = substr($temp1[1], 0, $pos);
                    $temp2[1] = substr($temp1[1], $pos+1);
                    $val = $value[$temp1[0]];
                    //$val = self::$temp2[0]($extra, $temp2[1], $val);
                    $val = call_user_func_array(array('\common\helpers\ExcelHelper',$temp2[0]),array($extra, $temp2[1], $val, $value));
                } else {
                    $val = $field? $value[$field] : $value;
                }
                $sheet->setCellValue($chr[$colIndex].$rowIndex, $val);
            }
            $rowIndex++;
        }

        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        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 .'"');
        header("Content-Transfer-Encoding: binary");
        header("Pragma: no-cache");
        $oWriter = \PHPExcel_IOFactory::createWriter($oExcel, 'Excel2007');
        $oWriter->save('php://output');
        $oExcel->disconnectWorksheets();
        exit;
    }

    /**
     * 導出
     * @see    https://www.cnblogs.com/tujia/p/5999806.html
     * @param  array    $titles         標題,一維數組,可傳map或單純標題
     * @param  array    $dataArray      數據,二維數組,可傳map或單純數據
     * @param  string   $filename       文件名,要帶后綴
     * @param  array    $extra          擴展數據
     * @return file
     */
    public static function exportSimple(array $titles, $dataArray, $filename, $extra=[])
    {
        // 后綴
        $suffix = substr($filename, strrpos($filename, '.'));
        empty($titles) && die('標題數組不能為空!');
        empty($dataArray) && die('數據數組不能為空!');
        !in_array($suffix, ['.xls', '.xlsx', '.csv']) && die('文件名格式錯誤!');

        // 導出准備
        set_time_limit(0);
        ini_set('memory_limit', '512M');

        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header('Content-Disposition: attachment; filename='.$filename);
        if ($suffix == '.xlsx') {
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        } elseif ($suffix == '.xls') {
            header('Content-Type: application/vnd.ms-excel');
        } elseif ($suffix == '.csv') {
            header('Content-Type: application/vnd.ms-excel; charset=gb18030');
        }
        header("Content-Transfer-Encoding: binary");
        header("Pragma: no-cache");

        $isCsv = ($suffix == '.csv');
        $fieldsCount = count($titles);
        if ($isCsv) {
            echo mb_convert_encoding(implode(',', array_values($titles)), 'gb18030') . "\n";
        } else {
            echo '<table>';
            echo '<tr>';
            foreach ($titles as $key => $value) {
                echo sprintf('<td>%s</td>', $value);
            }
            echo '</tr>';
        }
        foreach ($dataArray as $key => $value) {
            $i = 0;
            $isCsv==false && print('<tr>');
            foreach ($titles as $field => $title) {
                if (strrpos($field, '|') !== false) {
                    $temp1 = explode('|', $field);
                    $pos = strrpos($temp1[1], '.');
                    $pos === false && $pos = strlen($temp1[1]);
                    $temp2 = [];
                    $temp2[0] = substr($temp1[1], 0, $pos);
                    $temp2[1] = substr($temp1[1], $pos+1);
                    $val = $value[$temp1[0]];
                    //$val = self::$temp2[0]($extra, $temp2[1], $val);
                    $val = call_user_func_array(array('\common\helpers\ExcelHelper',$temp2[0]),array($extra, $temp2[1], $val, $value));
                } else {
                    $val = $field? $value[$field] : $value;
                }
                if ($isCsv) {
                    echo mb_convert_encoding($val . ($i == $fieldsCount-1? "\n":','), 'gb18030');
                } else {
                    if (isset(self::$styleFormat[$field])) {
                        echo sprintf("<td style='mso-number-format:\"%s\";'>%s</td>", self::$styleFormat[$field], $val); 
                    } else {
                        echo sprintf('<td>%s</td>', $val);
                    }
                }
                $i++;
            }
            $isCsv==false && print('</tr>');
        }
        $isCsv==false && print('</table>');
        exit;
    }

    public static function extra($extra, $extra_key, $val, $row)
    {
        $arr = ArrayHelper::getValue($extra, $extra_key, []);
        return ArrayHelper::getValue($arr, $val, '');
    }

    public static function dateIsEmpty($extra, $extra_key, $val, $row)
    {
        return strtotime($val)>1000? $val:'';
    }

    public static function toFixed($extra, $extra_key, $val, $row)
    {
        return (string)sprintf("%.{$extra_key}f", floatval($val));
    }

    public static function dateFormat($extra, $extra_key, $val, $row)
    {
        return date('Y-m-d H:i:s',$val/1000);
    }

    public static function trim($extra, $extra_key, $val, $row)
    {
        return str_replace(["\r", "\n", ","], ["", "", ","], $val);
    }

    public static function shopNameIsEmpty($extra, $extra_key, $val, $row)
    {
        return !empty($val)? $val:'個人發布';
    }

    public static function extraConcat($extra, $extra_key, $val, $row)
    {
        $arr = explode('-', $extra_key);
        foreach ($arr as $key => $value) {
            $val .= ArrayHelper::getValue($extra[$value.'Options'], $row[$value], '');
        }
        return $val;
    }
}

 

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

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM