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');
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章