suchen
HeimBackend-EntwicklungPHP-TutorialAusführliche Erläuterung zur Optimierung des PHP-Exports nach Excel

Hintergrund

Die Optimierung des PHP-Exports nach Excel wurde in meinem vorherigen Artikel vorgestellt: Gedanken zum PHP-Speicherüberlauf. In diesem Artikel wird hauptsächlich eine erweiterte Performance-Exportkomponente vorgestellt – ​​xlswriter , eine PHP-C-Erweiterung, klicken Sie bitte auf , um die offizielle Dokumentadresse anzuzeigen.

Empfohlen: PHP-Video-Tutorial

Installation

PECL installieren

Wenn wir feststellen, dass pecl nicht installiert ist, müssen wir pecl installieren. Im Allgemeinen wird es im PHP-Installationsverzeichnis installiert. Der Beispielbefehl lautet wie folgt:

# 进入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 配置

Verwenden Sie

Informationen zur spezifischen Verwendung finden Sie in der offiziellen Dokumentation. Hier ist der Code, den ich verwende:

Gekapselter Exportdienst

  /**
     * 下载
     * @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;
    }

Aufrufcode

Exportieren

    /**
     * 导出
     */
    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', '导出失败');
        }
    }

Importieren

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

Fazit

Nach der Gesamtnutzung ist die Leistung bei der Verarbeitung großer Datenmengen tatsächlich höher als das Original PHPExcel Viel.

Dieser Artikel wurde nachgedruckt, die Originaladresse lautet:

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

Das obige ist der detaillierte Inhalt vonAusführliche Erläuterung zur Optimierung des PHP-Exports nach Excel. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme
Dieser Artikel ist reproduziert unter:tsmliyun. Bei Verstößen wenden Sie sich bitte an admin@php.cn löschen
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么读取字符串后几个字符php怎么读取字符串后几个字符Apr 22, 2022 pm 08:31 PM

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么查找字符串是第几位php怎么查找字符串是第几位Apr 22, 2022 pm 06:48 PM

查找方法:1、用strpos(),语法“strpos("字符串值","查找子串")+1”;2、用stripos(),语法“strpos("字符串值","查找子串")+1”。因为字符串是从0开始计数的,因此两个函数获取的位置需要进行加1处理。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

See all articles

Heiße KI -Werkzeuge

Undresser.AI Undress

Undresser.AI Undress

KI-gestützte App zum Erstellen realistischer Aktfotos

AI Clothes Remover

AI Clothes Remover

Online-KI-Tool zum Entfernen von Kleidung aus Fotos.

Undress AI Tool

Undress AI Tool

Ausziehbilder kostenlos

Clothoff.io

Clothoff.io

KI-Kleiderentferner

AI Hentai Generator

AI Hentai Generator

Erstellen Sie kostenlos Ai Hentai.

Heiße Werkzeuge

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Leistungsstarke integrierte PHP-Entwicklungsumgebung

Sicherer Prüfungsbrowser

Sicherer Prüfungsbrowser

Safe Exam Browser ist eine sichere Browserumgebung für die sichere Teilnahme an Online-Prüfungen. Diese Software verwandelt jeden Computer in einen sicheren Arbeitsplatz. Es kontrolliert den Zugriff auf alle Dienstprogramme und verhindert, dass Schüler nicht autorisierte Ressourcen nutzen.

SAP NetWeaver Server-Adapter für Eclipse

SAP NetWeaver Server-Adapter für Eclipse

Integrieren Sie Eclipse mit dem SAP NetWeaver-Anwendungsserver.

WebStorm-Mac-Version

WebStorm-Mac-Version

Nützliche JavaScript-Entwicklungstools

Herunterladen der Mac-Version des Atom-Editors

Herunterladen der Mac-Version des Atom-Editors

Der beliebteste Open-Source-Editor