前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >如何快速导出百万级 Excel 数据

如何快速导出百万级 Excel 数据

作者头像
Mandy的名字被占用了
发布2021-01-04 10:56:30
2.2K0
发布2021-01-04 10:56:30
举报

文章介绍

今天分享一个 PHP 最好的一个 Excel 导出扩展。在日常的开发工作中,导出大量的 Excel 文件是必不可少的情况。之前做数据导出一般都是导出 csv 文件,或者使用 PHPexcel 扩展,导出 Excel 常见的问题就是,数据量大、内存消耗高。今天的这个扩展就很好的解决了这个问题。

安装扩展

该扩展已经是 PHP 的官方的扩展,安装的方式也有多种。官方推荐使用 pecl 方式安装,本文章中也是采用该方式安装。

代码语言:javascript
复制
pecl install xlswriter

扩展库地址:https://github.com/viest/php-ext-xlswriter 安装完之后就可以正常使用扩展了,官方在这基础上给到了一个基于 PHP 写的操作扩展库。

代码语言:javascript
复制
composer require --perfer-dist viest/php-ext-xlswriter-ide-helper:dev-master

代码示例

代码示例用了Spreadsheet,xlswriter两个扩展库做对比。基于几组数据做对别:

代码语言:javascript
复制
// 使用 xlswrite 扩展
public function xlsExport()
{
 $fileName = time() . '.xlsx';
 $config   = ['path' => public_path()];
 $excel    = new Excel($config);
 $data     = [];
 // 导出开始时间
 $startMemory = memory_get_usage();
 $t1          = microtime(true);

 for ($i = 0; $i < 1000000; $i++) {
  $data[$i] = [$i, $i, '张三'];
 }

 $excel->fileName($fileName, 'sheet1')
  ->header(['序号', '年龄', '张三'])
  ->data($data)
  ->output();

 // 导出结束时间
 $t2        = microtime(true);
 $endMemory = memory_get_usage();

 // 计算计算和内存差
 echo sprintf("内存使用: %f kb<br>", ($endMemory - $startMemory) / 1024) . PHP_EOL;
 echo sprintf("耗时: %f秒<br>", round($t2 - $t1, 3)) . PHP_EOL;
}

// 使用 phpspread 扩展
public function spreadExport()
{
 ini_set('max_execution_time', '10000000000');
 $fileName    = time() . '.xlsx';
 $spreadsheet = new Spreadsheet();
 $sheet       = $spreadsheet->getActiveSheet();

 // 导出开始时间
 $startMemory = memory_get_usage();
 $t1          = microtime(true);

 for ($i = 0; $i < 1000000; $i++) {
  $sheet->setCellValue('A' . $i, $i);
  $sheet->setCellValue('B' . $i, $i);
  $sheet->setCellValue('C' . $i, '张三');

 }
 $writer = new Xlsx($spreadsheet);
 $writer->save($fileName);

 // 导出结束时间
 $t2        = microtime(true);
 $endMemory = memory_get_usage();

 echo sprintf("内存使用: %f kb<br>", ($endMemory - $startMemory) / 1024) . PHP_EOL;
 echo sprintf("耗时: %f秒<br>", round($t2 - $t1, 3)) . PHP_EOL;
}

❝代码是在 Laravel 的基础上演示,因此部分函数是 Laravel 框架内置的函数。 ❞

性能对比

基于 xlswrite

基于 PHPspread

❝在使用 PHPspread 的是时候,设置了最大脚本超时时间。使用 PHP 默认的情况,直接执行脚本超时。 ❞

代码语言:javascript
复制
ini_set('max_execution_time', '10000000000');

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-12-21,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 卡二条的技术圈 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 文章介绍
  • 安装扩展
  • 代码示例
  • 性能对比
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档