今天小編給大家分享的是PHP如何導出Excel的優化詳解,很多人都不太了解,今天小編為了讓大家更加了解PHP如何導出Excel,所以給大家總結了以下內容,一起往下看吧。一定會有所收獲的哦。
背景
針對PHP導出Excel的優化,在我之前的一篇文章里已經做過介紹:關于PHP內存溢出的思考,本文主要是介紹一款高性能的導出組件–xlswriter,他是一個PHP C擴展。

安裝
安裝pecl
當我們發現pecl未安裝時,則需要安裝pecl。一般情況下,是安裝在PHP的安裝目錄,示例命令如下:
# 進入PHP安裝目錄 cd /usr/local/php/bin curl -o go-pear.php http://pear.php.net/go-pear.phar php go-pear.php # 安裝完成后,軟連接到bin目錄下 ln -s /usr/local/php/bin/pecl /usr/bin/pecl
安裝xlswriter
pecl install xlswriter # 添加 extension = xlswriter.so 到 ini 配置
使用
具體使用可以參考官方文檔,會介紹的更加詳細,我這就上一段我使用中的代碼:
封裝的導出service
/**
* 下載
* @param $header
* @param $data
* @param $fileName
* @param $type
* @return bool
* @throws
*/
public function download($header, $data, $fileName)
{
$config = [
'path' => $this->getTmpDir() . '/',
];
$now = date('YmdHis');
$fileName = $fileName . $now . '.xlsx';
$xlsxObject = new \Vtiful\Kernel\Excel($config);
// Init File
$fileObject = $xlsxObject->fileName($fileName);
// 設置樣式
$fileHandle = $fileObject->getHandle();
$format = new \Vtiful\Kernel\Format($fileHandle);
$style = $format->bold()->background(
\Vtiful\Kernel\Format::COLOR_YELLOW
)->align(Format::FORMAT_ALIGN_VERTICAL_CENTER)->toResource();
// Writing data to a file ......
$fileObject->header($header)
->data($data)
->freezePanes(1, 0)
->setRow('A1', 20, $style);
// Outptu
$filePath = $fileObject->output();
// 下載
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header('Content-Disposition: attachment;filename="' . $fileName . '"');
header('Cache-Control: max-age=0');
header('Content-Length: ' . filesize($filePath));
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate');
header('Pragma: public');
ob_clean();
flush();
if (copy($filePath, 'php://output') === false) {
throw new RuntimeException('導出失敗');
}
// Delete temporary file
@unlink($filePath);
return true;
}
/**
* 獲取臨時文件夾
* @return false|string
*/
private function getTmpDir()
{
// 目錄可以自定義
// return \Yii::$app->params['downloadPath'];
$tmp = ini_get('upload_tmp_dir');
if ($tmp !== False && file_exists($tmp)) {
return realpath($tmp);
}
return realpath(sys_get_temp_dir());
}
/**
* 讀取文件
* @param $path
* @param $fileName
* @return array
*/
public function readFile($path,$fileName)
{
// 讀取測試文件
$config = ['path' => $path];
$excel = new \Vtiful\Kernel\Excel($config);
$data = $excel->openFile($fileName)
->openSheet()
->getSheetData();
return $data;
}調用處代碼
導出
/**
* 導出
*/
public function actionExport()
{
try {
/**
* @var $searchModel SkuBarCodeSearch
*/
$searchModel = Yii::createObject(SkuBarCodeSearch::className());
$queryParams['SkuBarCodeSearch'] = [];
$result = $searchModel->search($queryParams, true);
$formatData = [];
if (!empty($result)) {
foreach ($result as $key => &$value) {
$tmpData = [
'sku_code' => $value['sku_code'],
'bar_code' => $value['bar_code'],
'created_at' => $value['created_at'],
'updated_at' => $value['updated_at'],
];
$formatData[] = array_values($tmpData);
}
unset($value);
}
$fields = [
'sku_code' => 'SKU編碼',
'bar_code' => '條形碼',
'created_at' => '創建時間',
'updated_at' => '更新時間',
];
/**
* @var $utilService UtilService
*/
$utilService = UtilService::getInstance();
$utilService->download(array_values($fields), $formatData, 'sku_single_code');
} catch (\Exception $e) {
Yii::$app->getSession()->setFlash('error', '導出失敗');
}
}導入
public function actionImportTmpSku()
{
try {
/**
* @var $utilService UtilService
*/
$utilService = UtilService::getInstance();
$path = '/tmp/'; // 文件目錄
$fileName = 'sku_0320.xlsx';
$excelData = $utilService->readFile($path, $fileName);
unset($excelData[0]);
$excelData = array_merge($excelData);
// ... ... 業務代碼
} catch (\Exception $e) {
echo $e->getMessage();
exit;
}
}結論
整體使用下來,在處理大數據量時,性能相比于原來的PHPExcel確實高了很多。
關于PHP如何導出Excel的優化詳解就分享到這里了,當然并不止以上和大家分析的辦法,不過小編可以保證其準確性是絕對沒問題的。希望以上內容可以對大家有一定的參考價值,可以學以致用。如果喜歡本篇文章,不妨把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。