


Detailed explanation of PHP using xlswriter to optimize Excel export performance (with code examples)
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.
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
https://github.com/viest/php-ext-xlswriterxlswriter Document
https://xlswriter-docs.viest.me/zh-cn/an-zhuang/huan-jing-yao-qiuDownload ide helper
composer require viest/php-ext-xlswriter-ide-helper:dev-masterBut 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.
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-fpmTest data: 20 columns, each column length is 19 English letters
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'); }}
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(); }}
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
Recommended learning: "
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!

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

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.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

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.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download
The most popular open source editor