搜索
首页后端开发php教程详解PHP用xlswriter优化Excel导出性能(附代码示例)

本篇文章给大家带来了关于php的相关知识,其中主要跟大家聊一聊xlswriter扩展是什么?怎么使用xlswriter扩展优化Excel导出性能,感兴趣的朋友下面一起来看一下吧,希望对大家有帮助。

关于xlswriter

xlswriter 是一个 PHP C 扩展,旨在提升php在导出大数据量时的性能问题,支持 windows / Linux 。可用于在 Excel 2007+ XLSX 文件中读取数据,插入多个工作表,写入文本、数字、公式、日期、图表、图片和超链接。

它具备以下特性:

一、写入

  • 100%兼容的 Excel XLSX 文件
  • 完整的 Excel 格式
  • 合并单元格
  • 定义工作表名称
  • 过滤器
  • 图表
  • 数据验证和下拉列表
  • 工作表 PNG/JPEG 图像
  • 用于写入大文件的内存优化模式
  • 适用于 Linux,FreeBSD,OpenBSD,OS X,Windows
  • 编译为 32 位和 64 位
  • FreeBSD 许可证
  • 唯一的依赖是 zlib

二、读取

  • 完整读取数据
  • 光标读取数据
  • 按数据类型读取
  • xlsx 转 CSV
  • 性能对比
  • 先感谢网友提供数据

下载安装

github源码

https://github.com/viest/php-ext-xlswriter

xlswriter 文档

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

下载 ide helper

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

但是我一直下载失败,于是去github仓库直接下载 https://github.com/viest/php-ext-xlswriter-ide-helper
然后将里面的几个类复制到一个 xlswriter_ide_helper.php 文件里面,将这个文件放到你的项目中就有代码提示了。

安装 xlswriter 扩展

此处在docker中安装

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

性能测试:

测试数据:20 列,每列长度为 19 英文字母

Xlswriter

c88e27d2dcfbb6772a494276bb3a342.jpg

PHPSpreadSheet

d943758d996c696c3cc6d48603ba640.jpg

PHP_XLSXWriter

80a430d822b78989ac01640e7c21ee0.jpg

使用示例:

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

如果发现下载的文件有时候打不开,那应该是你使用了官方的DEMO,问题出在 filesize(),这个函数是有缓存的,所以你会发现下载下来的文件和原始的文件大小不一样。要么像我一样不去设置 Content-Length,要么使用 clearstatcache()手动清除缓存。

实测5w条记录导出耗时1.5s,效果还是很强劲的。

导出效果
97762f1e30787a3829807ea8c9c09b1.jpg

推荐学习:《PHP视频教程

以上是详解PHP用xlswriter优化Excel导出性能(附代码示例)的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:csdn。如有侵权,请联系admin@php.cn删除
PHP依赖注入容器:快速启动PHP依赖注入容器:快速启动May 13, 2025 am 12:11 AM

aphpdepentioncontiveContainerIsatoolThatManagesClassDeptions,增强codemodocultion,可验证性和Maintainability.itactsasaceCentralHubForeatingingIndections,因此reducingTightCightTightCoupOulplingIndeSingantInting。

PHP中的依赖注入与服务定位器PHP中的依赖注入与服务定位器May 13, 2025 am 12:10 AM

选择DependencyInjection(DI)用于大型应用,ServiceLocator适合小型项目或原型。1)DI通过构造函数注入依赖,提高代码的测试性和模块化。2)ServiceLocator通过中心注册获取服务,方便但可能导致代码耦合度增加。

PHP性能优化策略。PHP性能优化策略。May 13, 2025 am 12:06 AM

phpapplicationscanbeoptimizedForsPeedAndeffificeby:1)启用cacheInphp.ini,2)使用preparedStatatementSwithPdoforDatabasequesies,3)3)替换loopswitharray_filtaray_filteraray_maparray_mapfordataprocrocessing,4)conformentnginxasaseproxy,5)

PHP电子邮件验证:确保正确发送电子邮件PHP电子邮件验证:确保正确发送电子邮件May 13, 2025 am 12:06 AM

phpemailvalidation invoLvesthreesteps:1)格式化进行regulareXpressecthemailFormat; 2)dnsvalidationtoshethedomainhasavalidmxrecord; 3)

如何使PHP应用程序更快如何使PHP应用程序更快May 12, 2025 am 12:12 AM

tomakephpapplicationsfaster,关注台词:1)useopcodeCachingLikeLikeLikeLikeLikePachetoStorePreciledScompiledScriptbyTecode.2)MinimimiedAtabaseSqueriSegrieSqueriSegeriSybysequeryCachingandeffeftExting.3)Leveragephp7 leveragephp7 leveragephp7 leveragephpphp7功能forbettercodeefficy.4)

PHP性能优化清单:立即提高速度PHP性能优化清单:立即提高速度May 12, 2025 am 12:07 AM

到ImprovephPapplicationspeed,关注台词:1)启用opcodeCachingwithapCutoredUcescriptexecutiontime.2)实现databasequerycachingusingpdotominiminimizedatabasehits.3)usehttp/2tomultiplexrequlexrequestsandredececonnection.4 limitsclection.4.4

PHP依赖注入:提高代码可检验性PHP依赖注入:提高代码可检验性May 12, 2025 am 12:03 AM

依赖注入(DI)通过显式传递依赖关系,显着提升了PHP代码的可测试性。 1)DI解耦类与具体实现,使测试和维护更灵活。 2)三种类型中,构造函数注入明确表达依赖,保持状态一致。 3)使用DI容器管理复杂依赖,提升代码质量和开发效率。

PHP性能优化:数据库查询优化PHP性能优化:数据库查询优化May 12, 2025 am 12:02 AM

databasequeryOptimizationinphpinvolVolVOLVESEVERSEVERSTRATEMIESOENHANCEPERANCE.1)SELECTONLYNLYNESSERSAYCOLUMNSTORMONTOUMTOUNSOUDSATATATATATATATATATATRANSFER.3)

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

安全考试浏览器

安全考试浏览器

Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。