PHP如何快速导出百万级数据的Excel文件

文章介绍

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

安装扩展

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

pecl install xlswriter

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

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

代码示例

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

// 使用 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 默认的情况,直接执行脚本超时。

ini_set('max_execution_time', '10000000000');
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章