当前位置:首页 > PHP教程 > 正文内容

关于PHP导出Excel的优化详解_php教程,PHP

搜教程4年前 (2020-03-31)PHP教程174

php获取文件夹中文件的两种方法_php教程

PHP即“超文本预处理器”,是一种通用开源脚本语言。是常用的网站编程语言。本文就来为大家介绍php中两种获取文件夹中文件的方法。

背景

针对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

安装xlswriter

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

使用

具体使用可以参考官方文档,会介绍的更加详细,我这就上一段我使用中的代码:

关于检测文件是否有病毒的PHP实现逻辑_php教程

在用户收到发送过来的文件后 , 要能够检测出这个文件是否是病毒 , 核心的软件是clamav , 可以在linux命令行执行,检测文件或目录里的病毒。

封装的导出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确实高了很多。

本文系转载,原文地址是:

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

以上就是关于PHP导出Excel的优化详解的详细内容,更多请关注ki4网其它相关文章!

PHP设置setcookie的方法实例_php教程

setcookie()函数向客户端发送一个HTTP cookie。cookie是由服务器发送到浏览器的变量。本文就来为大家介绍一下php设置setcookie的方法。

扫描二维码推送至手机访问。

版权声明:本文由搜教程网发布,如需转载请注明出处。

本文链接:https://www.sojiaocheng.cn/17447.html

标签: PHP
分享给朋友:

“关于PHP导出Excel的优化详解_php教程,PHP” 的相关文章

PHP怎样运用换行符?(代码示例)【php教程】,PHP,换行符

PHP怎样运用换行符?(代码示例)【php教程】,PHP,换行符

在PHP剧本中偶然须要举行换行输出,那末怎样举行换行?下面本篇文章就来给人人引见一下在PHP中怎样运用换行符举行换行,愿望对人人有所协助。 要领一:运用PHP换行符 换行符是用于回避继承运用相偕行的分隔符。这是为了将冗杂的线分红小的,易读的块,逐行显现。PHP许可经由过程运用转义序列或预...

怎样从PHP中的字符串中删除换行符?(代码示例)【php教程】,PHP,str_replace(),preg_replace()

怎样从PHP中的字符串中删除换行符?(代码示例)【php教程】,PHP,str_replace(),preg_replace()

在PHP中能够运用内置函数:str_replace()函数或preg_replace()函数来删除字符串中的换行符,下面本篇文章就来带人人相识一下这两个函数是怎样删除换行符的,愿望对人人有所协助。 要领一:运用str_replace()函数 str_replace()函数能够用于以其...

php会话(Session)接见限定的引见(代码示例)【php教程】,php

本篇文章给人人带来的内容是关于php会话(Session)接见限定的引见(代码示例),有肯定的参考价值,有须要的朋侪能够参考一下,愿望对你有所协助。 登录 <?php // 启动会话 session_start(); // 注册上岸胜利的 admin 变量,并赋值...

PHP怎样完成斐波那契数列?(代码实例)【php教程】,PHP,斐波那契数列

PHP怎样完成斐波那契数列?(代码实例)【php教程】,PHP,斐波那契数列

斐波那契数列(Fibonacci sequence),又称黄金分割数列、因数学家列昂纳多·斐波那契(Leonardoda Fibonacci)以兔子滋生为例子而引入,故又称为“兔子数列”,指的是如许一个数列:1、1、2、3、5、8、13、21、34、……,简朴来讲,斐波那契数列就是一系列元素,前两个...

PHP运用递归生成子数组(代码实例)【php教程】,PHP递归,子数组

PHP运用递归生成子数组(代码实例)【php教程】,PHP递归,子数组

给定一个数组,运用递归生成给定数组的一切能够的子数组。本篇文章就将给人人引见如何用PHP来完成此功用。 例子: 输入:[1,2,3] 输出:[1],[1,2],[2],[1,2,3],[2,3],[3] 输入:[1,2] 输出:[1],[1,2],[2] 要领: 我们运用两个指针star...

如安在CentOS / RHEL 6.10上装置PHP( 7.3,7.2,7.1)?【php教程】,CentOS,RHEL,PHP7.3,PHP7.2,PHP7.1

PHP 7.3是PHP最新的稳固版本。本文将给人人引见如安在CentOS和Redhat 6.10体系上装置PHP 7.3、PHP 7.2、PHP 7.1。 设置yum库 起首,须要在体系上启用Remi和EPEL yum存储库。运用以下敕令在CentOS和Red Hat 7/6体系上装置EPE...