PHP Excelエクスポートの最適化について詳しく解説

藏色散人
リリース: 2023-04-08 13:52:01
転載
3117 人が閲覧しました

背景

PHP の Excel へのエクスポートの最適化については、以前の記事で紹介しました: PHP のメモリ オーバーフローについて考えるこの記事では、主に高度なパフォーマンス エクスポート コンポーネントである xlswriter を紹介します。 、これは PHP C 拡張機能です。公式ドキュメントのアドレスについては、クリックをご覧ください。

推奨: PHP ビデオ チュートリアル

インストール

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
ログイン後にコピー

Install xlswriter

pecl install xlswriter
# 添加 extension = xlswriter.so 到 ini 配置
ログイン後にコピー

Use

具体的な使い方については、詳しく紹介する公式ドキュメントを参照してください。使用しているコードは次のとおりです:

カプセル化されたエクスポート サービス

  /**
     * 下载
     * @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がたくさんあります。

この記事は転載されており、元のアドレスは次のとおりです:

https://tsmliyun.github.io/php/PHP Optimization of Excel Export/

以上がPHP Excelエクスポートの最適化について詳しく解説の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

関連ラベル:
php
ソース:github.io
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
最新の問題
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!