Home Backend Development PHP Tutorial Detailed explanation of PHP using xlswriter to optimize Excel export performance (with code examples)

Detailed explanation of PHP using xlswriter to optimize Excel export performance (with code examples)

Feb 24, 2023 pm 03:46 PM
php excel xlswriter

This article brings you relevant knowledge about PHP, and mainly talks about what is the xlswriter extension? How to use the xlswriter extension to optimize Excel export performance. Friends who are interested can take a look below. I hope it will be helpful to everyone.

About xlswriter

xlswriter is a PHP C extension designed to improve the performance of PHP when exporting large amounts of data. It supports windows / Linux. Can be used to read data in Excel 2007 XLSX files, insert multiple worksheets, write text, numbers, formulas, dates, charts, pictures and hyperlinks.

It has the following features:

1. Write

  • 100% compatible Excel XLSX file
  • Full Excel format
  • Merge cells
  • Define worksheet name
  • Filter
  • Chart
  • Data Validation and dropdown lists
  • Worksheet PNG/JPEG images
  • Memory optimized mode for writing large files
  • Works with Linux, FreeBSD, OpenBSD, OS X, Windows
  • Compiled for 32-bit and 64-bit
  • FreeBSD License
  • The only dependency is zlib

2. Read

  • Read data completely
  • Read data with cursor
  • Read by data type
  • xlsx to CSV
  • Performance comparison
  • Thank you in advance for providing data

Download and installation

##github source code

https://github.com/viest/php-ext-xlswriter
Copy after login

xlswriter Document

https://xlswriter-docs.viest.me/zh-cn/an-zhuang/huan-jing-yao-qiu
Copy after login

Download ide helper

composer require viest/php-ext-xlswriter-ide-helper:dev-master
Copy after login

But I kept failing to download, so I went to the github warehouse to download directly https://github.com/viest/php-ext-xlswriter-ide -helper

Then copy several classes inside to a xlswriter_ide_helper.php file. Put this file into your project and you will get code prompts.

Install xlswriter extension

Install in docker here

docker exec -it php72-fpm bashcd /usr/local/bin
pecl install xlswriter
docker-php-ext-enable xlswriter
php -m

php --ri xlswriter
Version => 1.3.6

docker restart php72-fpm
Copy after login

Performance Test:

Test data: 20 columns, each column length is 19 English letters

Xlswriter

Detailed explanation of PHP using xlswriter to optimize Excel export performance (with code examples)

PHPSpreadSheet

Detailed explanation of PHP using xlswriter to optimize Excel export performance (with code examples)

##PHP_XLSXWriter

Detailed explanation of PHP using xlswriter to optimize Excel export performance (with code examples)Usage example:

private function rankPersonExport($activityInfo, $list){
    $date = date('Y-m-d');
    $filename = "{$activityInfo['orgname']}-{$activityInfo['name']}-个人排行榜-{$date}";
    $header = ['名次', '用户ID', '对接账号', '姓名', '电话', '部门ID', '一级部门', '二级部门', '三级部门', '总积分', '最后积分时间', "毫秒"];
    if (!empty($activityInfo['ext'])) {
        $extArr = json_decode($activityInfo['ext'], true);
        foreach ($extArr as $errItem) {
            array_push($header, $errItem['name']);
        }
    }
    // list
    $listVal = [];
    foreach($list as $v){
        $temp = [
            $v['rank'],
            $v['userid'],
            $v['userName'],
            $v['nickName'],
            $v['phone'],
            $v['departid'],
            $v['topDepartName'],
            $v['secDepartName'],
            $v['thirdDepartName'],
            $v['score'],
            $v['updatetime'],
            $v['micro'],
        ];

        if (!empty($v['ext'])) {
            $extArr = explode('|', $v['ext']);
            foreach ($extArr as $k2 => $v2) {
                $errItemArr = explode('^', $v2);
                array_push($temp, $errItemArr[1]);
            }
        }
        array_push($listVal, $temp);
    }

    $re = downloadXLSX($filename, $header, $listVal);
    if($re){
        return $this->output(0, $re);
    }else{
        return $this->output(1, 'success');
    }}
Copy after login
function getTmpDir(): string{
    $tmp = ini_get('upload_tmp_dir');

    if ($tmp !== False && file_exists($tmp)) {
        return realpath($tmp);
    }

    return realpath(sys_get_temp_dir());}/**
 * download xlsx file
 *
 * @param string $filename
 * @param array $header
 * @param array $list
 * @return string errmsg
 */function downloadXLSX(string $filename, array $header, array $list): string{
    try {
        $config = ['path' => getTmpDir() . '/'];
        $excel  = (new \Vtiful\Kernel\Excel($config))->fileName($filename.'.xlsx', 'Sheet1');
        $fileHandle = $excel->getHandle();
        $format1    = new \Vtiful\Kernel\Format($fileHandle);
        $format2    = new \Vtiful\Kernel\Format($fileHandle);

        // title style
        $titleStyle = $format1->fontSize(16)
            ->bold()
            ->font("Calibri")
            ->align(\Vtiful\Kernel\Format::FORMAT_ALIGN_CENTER, \Vtiful\Kernel\Format::FORMAT_ALIGN_VERTICAL_CENTER)
            ->toResource();

        // global style
        $globalStyle = $format2->fontSize(10)
            ->font("Calibri")
            ->align(\Vtiful\Kernel\Format::FORMAT_ALIGN_CENTER, \Vtiful\Kernel\Format::FORMAT_ALIGN_VERTICAL_CENTER)
            ->border(\Vtiful\Kernel\Format::BORDER_THIN)
            ->toResource();

        $headerLen = count($header);

        // header
        array_unshift($list, $header);

        // title
        $title = array_fill(1, $headerLen - 1, '');
        $title[0] = $filename;
        array_unshift($list, $title);

        $end = strtoupper(chr(65 + $headerLen - 1));
        // column style
        $excel->setColumn("A:{$end}", 15, $globalStyle);
        // title
        $excel->MergeCells("A1:{$end}1", $filename)->setRow("A1", 25, $titleStyle);
        // 冻结前两行,列不冻结
        $excel->freezePanes(2, 0);
        // 数据
        $filePath = $excel->data($list)->output();

        header("Content-Disposition:attachment;filename={$filename}.xlsx");

        $re = copy($filePath, 'php://output');
        if ($re === false) {
            $err = 'failed to write output';
        } else {
            $err = '';
        }
        @unlink($filePath);

        return $err;
    } catch (\Vtiful\Kernel\Exception $e) {
        return $e->getMessage();
    }}
Copy after login

If you find that the downloaded file sometimes cannot be opened, it should be that you have used the official DEMO. The problem lies in filesize( ), this function is cached, so you will find that the size of the downloaded file is different from the original file. Either don't set Content-Length like I did, or clear the cache manually using clearstatcache().

Accurately, it takes 1.5s to export 50,000 records, and the effect is still very strong.

Export effect


Detailed explanation of PHP using xlswriter to optimize Excel export performance (with code examples) Recommended learning: "

PHP Video Tutorial

"

The above is the detailed content of Detailed explanation of PHP using xlswriter to optimize Excel export performance (with code examples). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1262
29
C# Tutorial
1236
24
How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

See all articles