search
HomeBackend DevelopmentPHP TutorialHow to use xlswriter in PHP to import and export big data? (detailed explanation)

How does PHP use xlswriter to import and export big data? The following article will introduce to you the method of importing and exporting PHP big data xlswriter (optimal dataization). I hope it will be helpful to you!

How to use xlswriter in PHP to import and export big data? (detailed explanation)

This article introduces the Vtiful\Kernel\Excel class based on the PHP extension xlswriter, which can support unlimited levels of complex header export! We may continue to update and optimize in the future

1. Prepare xlswriter extension

1. Windows system:

Go to the PECL website to download the ddl file that matches your local PHP environment. Download address: https://pecl.php.net/package/xlswriter, and copy it to the PHP extension directory ext folder, modify the php.ini file,

Add this line

extension=xlswriter

2. Linux system:

Use the command to install

pecl install xlswriter

php configuration file addition

extension = xlswriter.so

Restart: php nginx View PHP installation xlswriter extension

##2. Encapsulate export class files (here comes the key point)
<?php

namespace App\Services;

use Vtiful\Kernel\Excel;

class MultiFloorXlsWriterService
{
    // 默认宽度
    private $defaultWidth = 16;
    // 默认导出格式
    private $exportType = &#39;.xlsx&#39;;
    // 表头最大层级
    private $maxHeight = 1;
    // 文件名
    private $fileName = null;

    private $xlsObj;
    private $fileObject;
    private $format;

    /**
     * MultiFloorXlsWriterService constructor.
     * @throws \App\Exceptions\ApiException
     */
    public function __construct()
    {
        // 文件默认输出地址
        $path = base_path().&#39;/public/uploads/excel&#39;;
        $config = [
            &#39;path&#39; => $path
        ];

        $this->xlsObj = (new \Vtiful\Kernel\Excel($config));
    }

    /**
     * 设置文件名
     * @param string $fileName
     * @param string $sheetName
     * @author LWW
     */
    public function setFileName(string $fileName = &#39;&#39;, string $sheetName = &#39;Sheet1&#39;)
    {
        $fileName = empty($fileName) ? (string)time() : $fileName;
        $fileName .= $this->exportType;

        $this->fileName = $fileName;

        $this->fileObject = $this->xlsObj->fileName($fileName, $sheetName);
        $this->format = (new \Vtiful\Kernel\Format($this->fileObject->getHandle()));
    }

    /**
     * 设置表头
     * @param array $header
     * @param bool $filter
     * @throws \Exception
     * @author LWW
     */
    public function setHeader(array $header, bool $filter = false)
    {
        if (empty($header)) {
            throw new \Exception(&#39;表头数据不能为空&#39;);
        }

        if (is_null($this->fileName)) {
            self::setFileName(time());
        }

        // 获取单元格合并需要的信息
        $colManage = self::setHeaderNeedManage($header);

        // 完善单元格合并信息
        $colManage = self::completeColMerge($colManage);

        // 合并单元格
        self::queryMergeColumn($colManage, $filter);

    }

    /**
     * 填充文件数据
     * @param array $data
     * @author LWW
     */
    public function setData(array $data)
    {
        foreach ($data as $row => $datum) {
            foreach ($datum as $column => $value) {
                $this->fileObject->insertText($row + $this->maxHeight, $column, $value);
            }
        }
    }

    /**
     * 添加Sheet
     * @param string $sheetName
     * @author LWW
     */
    public function addSheet(string $sheetName)
    {
        $this->fileObject->addSheet($sheetName);
    }

    /**
     * 保存文件至服务器
     * @return mixed
     * @author LWW
     */
    public function output()
    {
        return $this->fileObject->output();
    }

    /**
     * 输出到浏览器
     * @param string $filePath
     * @throws \Exception
     * @author LWW
     */
    public function excelDownload(string $filePath)
    {
        $fileName = $this->fileName;
        $userBrowser = $_SERVER[&#39;HTTP_USER_AGENT&#39;];
        if (preg_match(&#39;/MSIE/i&#39;, $userBrowser)) {
            $fileName = urlencode($fileName);
        } else {
            $fileName = iconv(&#39;UTF-8&#39;, &#39;GBK//IGNORE&#39;, $fileName);
        }

        header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        header(&#39;Content-Disposition: attachment;filename="&#39; . $fileName . &#39;"&#39;);
        header(&#39;Content-Length: &#39; . filesize($filePath));
        header(&#39;Content-Transfer-Encoding: binary&#39;);
        header(&#39;Cache-Control: must-revalidate&#39;);
        header(&#39;Cache-Control: max-age=0&#39;);
        header(&#39;Pragma: public&#39;);

        if (ob_get_contents()) {
            ob_clean();
        }

        flush();

        if (copy($filePath, &#39;php://output&#39;) === false) {
            throw new \Exception($filePath . &#39;地址出问题了&#39;);
        }

        // 删除本地文件
        @unlink($filePath);

        exit();
    }

    /**
     * 组装单元格合并需要的信息
     * @param array $header
     * @param int $col
     * @param int $cursor
     * @param array $colManage
     * @param null $parent
     * @param array $parentList
     * @return array
     * @throws \Exception
     * @author LWW
     */
    private function setHeaderNeedManage(array $header,int $col = 1,int &$cursor = 0,array &$colManage = [], $parent = null,array $parentList = [])
    {
        foreach ($header as $head) {
            if (empty($head[&#39;title&#39;])) {
                throw new \Exception(&#39;表头数据格式有误&#39;);
            }

            if (is_null($parent)) {
                // 循环初始化
                $parentList = [];
                $col = 1;
            } else {
                // 递归进入,高度和父级集合通过相同父级条件从已有数组中获取,避免递归增加与实际数据不符
                foreach ($colManage as $value) {
                    if ($value[&#39;parent&#39;] == $parent) {
                        $parentList = $value[&#39;parentList&#39;];
                        $col = $value[&#39;height&#39;];
                        break;
                    }
                }
            }

            // 单元格标识
            $column = $this->getColumn($cursor) . $col;

            // 组装单元格需要的各种信息
            $colManage[$column] = [
                &#39;title&#39;      => $head[&#39;title&#39;],      // 标题
                &#39;cursor&#39;     => $cursor,             // 游标
                &#39;cursorEnd&#39;  => $cursor,             // 结束游标
                &#39;height&#39;     => $col,                // 高度
                &#39;width&#39;      => $this->defaultWidth, // 宽度
                &#39;mergeStart&#39; => $column,             // 合并开始标识
                &#39;hMergeEnd&#39;  => $column,             // 横向合并结束标识
                &#39;zMergeEnd&#39;  => $column,             // 纵向合并结束标识
                &#39;parent&#39;     => $parent,             // 父级标识
                &#39;parentList&#39; => $parentList,         // 父级集合
            ];

            if (isset($head[&#39;children&#39;]) && !empty($head[&#39;children&#39;]) && is_array($head[&#39;children&#39;])) {
                // 有下级,高度加一
                $col += 1;
                // 当前标识加入父级集合
                $parentList[] = $column;

                $this->setHeaderNeedManage($head[&#39;children&#39;], $col, $cursor, $colManage, $column, $parentList);
            } else {
                // 没有下级,游标加一
                $cursor += 1;
            }
        }

        return $colManage;
    }

    /**
     * 完善单元格合并信息
     * @param array $colManage
     * @return mixed
     * @author LWW
     */
    private function completeColMerge(array $colManage)
    {
        $this->maxHeight = max(array_column($colManage, &#39;height&#39;));
        $parentManage = array_column($colManage, &#39;parent&#39;);

        foreach ($colManage as $index => $value) {
            // 设置横向合并结束范围:存在父级集合,把所有父级的横向合并结束范围设置为当前单元格
            if (!is_null($value[&#39;parent&#39;]) && !empty($value[&#39;parentList&#39;])) {
                foreach ($value[&#39;parentList&#39;] as $parent) {
                    $colManage[$parent][&#39;hMergeEnd&#39;] = self::getColumn($value[&#39;cursor&#39;]) . $colManage[$parent][&#39;height&#39;];
                    $colManage[$parent][&#39;cursorEnd&#39;] = $value[&#39;cursor&#39;];
                }
            }

            // 设置纵向合并结束范围:当前高度小于最大高度 且 不存在以当前单元格标识作为父级的项
            $checkChildren = array_search($index, $parentManage);
            if ($value[&#39;height&#39;] < $this->maxHeight && !$checkChildren) {
                $colManage[$index][&#39;zMergeEnd&#39;] = self::getColumn($value[&#39;cursor&#39;]) . $this->maxHeight;
            }
        }

        return $colManage;
    }

    /**
     * 合并单元格
     * @param array $colManage
     * @param bool $filter
     * @author LWW
     */
    private function queryMergeColumn(array $colManage,bool $filter)
    {
        foreach ($colManage as $value) {
            $this->fileObject->mergeCells("{$value[&#39;mergeStart&#39;]}:{$value[&#39;zMergeEnd&#39;]}", $value[&#39;title&#39;]);
            $this->fileObject->mergeCells("{$value[&#39;mergeStart&#39;]}:{$value[&#39;hMergeEnd&#39;]}", $value[&#39;title&#39;]);

            // 设置单元格需要的宽度
            if ($value[&#39;cursor&#39;] != $value[&#39;cursorEnd&#39;]) {
                $value[&#39;width&#39;] = ($value[&#39;cursorEnd&#39;] - $value[&#39;cursor&#39;] + 1) * $this->defaultWidth;
            }

            // 设置列单元格样式
            $toColumnStart = self::getColumn($value[&#39;cursor&#39;]);
            $toColumnEnd = self::getColumn($value[&#39;cursorEnd&#39;]);
            $this->fileObject->setColumn("{$toColumnStart}:{$toColumnEnd}", $value[&#39;width&#39;]);
        }

        // 是否开启过滤选项
        if ($filter) {
            // 获取最后的单元格标识
            $filterEndColumn = self::getColumn(end($colManage)[&#39;cursorEnd&#39;]) . $this->maxHeight;
            $this->fileObject->autoFilter("A1:{$filterEndColumn}");
        }
    }

    /**
     * 获取单元格列标识
     * @param int $num
     * @return string
     * @author LWW
     */
    private function getColumn(int $num)
    {
        return Excel::stringFromColumnIndex($num);
    }
}

3. Usage example

The code is as follows

    /**
     * 导出测试
     * @author LWW
     */
    public function export()
    {
        $header = [
            [
                &#39;title&#39; => &#39;一级表头1&#39;,
                &#39;children&#39; => [
                    [
                        &#39;title&#39; => &#39;二级表头1&#39;,
                    ],
                    [
                        &#39;title&#39; => &#39;二级表头2&#39;,
                    ],
                    [
                        &#39;title&#39; => &#39;二级表头3&#39;,
                    ],
                ]
            ],
            [
                &#39;title&#39; => &#39;一级表头2&#39;
            ],
            [
                &#39;title&#39; => &#39;一级表头3&#39;,
                &#39;children&#39; => [
                    [
                        &#39;title&#39; => &#39;二级表头1&#39;,
                        &#39;children&#39; => [
                            [
                                &#39;title&#39; => &#39;三级表头1&#39;,
                            ],
                            [
                                &#39;title&#39; => &#39;三级表头2&#39;,
                            ],
                        ]
                    ],
                    [
                        &#39;title&#39; => &#39;二级表头2&#39;,
                    ],
                    [
                        &#39;title&#39; => &#39;二级表头3&#39;,
                        &#39;children&#39; => [
                            [
                                &#39;title&#39; => &#39;三级表头1&#39;,
                                &#39;children&#39; => [
                                    [
                                        &#39;title&#39; => &#39;四级表头1&#39;,
                                        &#39;children&#39; => [
                                            [
                                                &#39;title&#39; => &#39;五级表头1&#39;
                                            ],
                                            [
                                                &#39;title&#39; => &#39;五级表头2&#39;
                                            ]
                                        ]
                                    ],
                                    [
                                        &#39;title&#39; => &#39;四级表头2&#39;
                                    ]
                                ]
                            ],
                            [
                                &#39;title&#39; => &#39;三级表头2&#39;,
                            ],
                        ]
                    ]
                ]
            ],
            [
                &#39;title&#39; => &#39;一级表头4&#39;,
            ],
            [
                &#39;title&#39; => &#39;一级表头5&#39;,
            ],
        ];
        $data= [];
        // header头规则 title表示列标题,children表示子列,没有子列children可不写或为空
        for ($i = 0; $i < 100; $i++) {
            $data[] = [
                &#39;这是第&#39;. $i .&#39;行测试&#39;,
                &#39;这是第&#39;. $i .&#39;行测试&#39;,
                &#39;这是第&#39;. $i .&#39;行测试&#39;,
                &#39;这是第&#39;. $i .&#39;行测试&#39;,
                &#39;这是第&#39;. $i .&#39;行测试&#39;,
                &#39;这是第&#39;. $i .&#39;行测试&#39;,
                &#39;这是第&#39;. $i .&#39;行测试&#39;,
                &#39;这是第&#39;. $i .&#39;行测试&#39;,
                &#39;这是第&#39;. $i .&#39;行测试&#39;,
                &#39;这是第&#39;. $i .&#39;行测试&#39;,
                &#39;这是第&#39;. $i .&#39;行测试&#39;,
                &#39;这是第&#39;. $i .&#39;行测试&#39;,
                &#39;这是第&#39;. $i .&#39;行测试&#39;,
            ];
        }
        $fileName = &#39;很厉害的文件导出类&#39;;
        $xlsWriterServer = new MultiFloorXlsWriterService();
        $xlsWriterServer->setFileName($fileName, &#39;这是Sheet1别名&#39;);
        $xlsWriterServer->setHeader($header, true);
        $xlsWriterServer->setData($data);

        $xlsWriterServer->addSheet(&#39;这是Sheet2别名&#39;);
        $xlsWriterServer->setHeader($header);   //这里可以使用新的header
        $xlsWriterServer->setData($data);       // 这里也可以根据新的header定义数据格式

        $filePath = $xlsWriterServer->output();     // 保存到服务器
        $xlsWriterServer->excelDownload($filePath); // 输出到浏览器
    }

Export effect


Recommended learning:《

PHP video tutorial

The above is the detailed content of How to use xlswriter in PHP to import and export big data? (detailed explanation). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:learnku. If there is any infringement, please contact admin@php.cn delete
How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

Simple Guide: Sending Email with PHP ScriptSimple Guide: Sending Email with PHP ScriptMay 12, 2025 am 12:02 AM

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP Performance: Identifying and Fixing BottlenecksPHP Performance: Identifying and Fixing BottlenecksMay 11, 2025 am 12:13 AM

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

Dependency Injection for PHP: a quick summaryDependency Injection for PHP: a quick summaryMay 11, 2025 am 12:09 AM

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

Increase PHP Performance: Caching Strategies & TechniquesIncrease PHP Performance: Caching Strategies & TechniquesMay 11, 2025 am 12:08 AM

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version