PHP 導出 Excel 的優化

背景

針對PHP導出Excel的優化,在我以前的一篇文章裏已經作過介紹:關於PHP內存溢出的思考,本文主要是介紹一款高性能的導出組件--xlswriter,他是一個PHP C擴展,官方文檔地址,請點擊php

安裝

安裝pecl

當咱們發現pecl未安裝時,則須要安裝pecl。通常狀況下,是安裝在PHP的安裝目錄,示例命令以下:git

# 進入PHP安裝目錄
cd /usr/local/php/bin

curl -o go-pear.php http://pear.php.net/go-pear.phar

php go-pear.php

# 安裝完成後,軟鏈接到bin目錄下
ln -s /usr/local/php/bin/pecl /usr/bin/pecl

安裝xlswriter

pecl install xlswriter

# 添加 extension = xlswriter.so 到 ini 配置

使用

具體使用能夠參考官方文檔,會介紹的更加詳細,我這就上一段我使用中的代碼:github

封裝的導出service

/**
     * 下載
     * @param $header
     * @param $data
     * @param $fileName
     * @param $type
     * @return bool
     * @throws
     */
    public function download($header, $data, $fileName)
    {
        $config     = [
            'path' => $this->getTmpDir() . '/',
        ];
        $now        = date('YmdHis');
        $fileName   = $fileName . $now . '.xlsx';
        $xlsxObject = new \Vtiful\Kernel\Excel($config);

        // Init File
        $fileObject = $xlsxObject->fileName($fileName);

        // 設置樣式
        $fileHandle = $fileObject->getHandle();
        $format     = new \Vtiful\Kernel\Format($fileHandle);
        $style      = $format->bold()->background(
            \Vtiful\Kernel\Format::COLOR_YELLOW
        )->align(Format::FORMAT_ALIGN_VERTICAL_CENTER)->toResource();

        // Writing data to a file ......
        $fileObject->header($header)
            ->data($data)
            ->freezePanes(1, 0)
            ->setRow('A1', 20, $style);

        // Outptu
        $filePath = $fileObject->output();


                // 下載
                 header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        header('Content-Disposition: attachment;filename="' . $fileName . '"');
        header('Cache-Control: max-age=0');
        header('Content-Length: ' . filesize($filePath));
        header('Content-Transfer-Encoding: binary');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        ob_clean();
        flush();
        if (copy($filePath, 'php://output') === false) {
            throw new RuntimeException('導出失敗');
        }
      
        // Delete temporary file
        @unlink($filePath);

        return true;
    }

    /**
     * 獲取臨時文件夾
     * @return false|string
     */
    private function getTmpDir()
    {
          // 目錄能夠自定義
          // return \Yii::$app->params['downloadPath'];
      
        $tmp = ini_get('upload_tmp_dir');
        if ($tmp !== False && file_exists($tmp)) {
            return realpath($tmp);
        }
        return realpath(sys_get_temp_dir());
    }

    /**
     * 讀取文件
     * @param $path
     * @param $fileName
     * @return array
     */
    public function readFile($path,$fileName)
    {
        // 讀取測試文件
        $config = ['path' => $path];
        $excel  = new \Vtiful\Kernel\Excel($config);
        $data   = $excel->openFile($fileName)
            ->openSheet()
            ->getSheetData();
        return $data;
    }

調用處代碼

導出

/**
     * 導出
     */
    public function actionExport()
    {
        try {
            /**
             * @var $searchModel SkuBarCodeSearch
             */
            $searchModel                     = Yii::createObject(SkuBarCodeSearch::className());
            $queryParams['SkuBarCodeSearch'] = [];

            $result = $searchModel->search($queryParams, true);

            $formatData = [];
            if (!empty($result)) {
                foreach ($result as $key => &$value) {
                    $tmpData      = [
                        'sku_code'   => $value['sku_code'],
                        'bar_code'   => $value['bar_code'],
                        'created_at' => $value['created_at'],
                        'updated_at' => $value['updated_at'],
                    ];
                    $formatData[] = array_values($tmpData);
                }
                unset($value);
            }

            $fields = [
                'sku_code'   => 'SKU編碼',
                'bar_code'   => '條形碼',
                'created_at' => '建立時間',
                'updated_at' => '更新時間',
            ];

            /**
             * @var $utilService UtilService
             */
            $utilService = UtilService::getInstance();
            $utilService->download(array_values($fields), $formatData, 'sku_single_code');
        } catch (\Exception $e) {
            Yii::$app->getSession()->setFlash('error', '導出失敗');
        }
    }

導入

public function actionImportTmpSku()
    {
        try {
            /**
             * @var $utilService UtilService
             */
            $utilService = UtilService::getInstance();
            $path        = '/tmp/'; // 文件目錄
            $fileName    = 'sku_0320.xlsx';
            $excelData   = $utilService->readFile($path, $fileName);

            unset($excelData[0]);
            $excelData = array_merge($excelData);

               // ... ... 業務代碼

        } catch (\Exception $e) {
            echo $e->getMessage();
            exit;
        }
    }

結論

總體使用下來,在處理大數據量時,性能相比於原來的PHPExcel確實高了不少。文章中如有錯誤,歡迎指出。shell

文章首發地址:https://tsmliyun.github.io/ph...app

相關文章
相關標籤/搜索