關於PHP匯出Excel的優化詳解

2020-07-16 10:05:54
背景

安裝

安裝pecl

當我們發現pecl未安裝時,則需要安裝pecl。一般情況下,是安裝在PHP的安裝目錄,範例命令如下:

# 進入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 設定

使用

具體使用可以參考官方文件,會介紹的更加詳細,我這就上一段我使用中的程式碼:

封裝的匯出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 VtifulKernelExcel($config);
        // Init File
        $fileObject = $xlsxObject->fileName($fileName);
        // 設定樣式
        $fileHandle = $fileObject->getHandle();
        $format     = new VtifulKernelFormat($fileHandle);
        $style      = $format->bold()->background(
            VtifulKernelFormat::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 VtifulKernelExcel($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確實高了很多。

本文系轉載,原文地址是:

https://tsmliyun.github.io/php/PHP%E5%AF%BC%E5%87%BAExcel%E7%9A%84%E4%BC%98%E5%8C%96/

以上就是關於PHP匯出Excel的優化詳解的詳細內容,更多請關注TW511.COM其它相關文章!