利用phpspreadsheet可以輕鬆的解析excel檔案,但是phpspreadsheet的記憶體消耗也是比較大的,我試過解析將近5M的純文字excel記憶體使用量就會超過php預設的最大記憶體128M。
當然這可以用調節記憶體大小的方法來解決,但是在並行量大的時候就比較危險了。所以今天介紹下一種方法,利用phpspreadsheet對excel檔案進行切割,這是個拿時間換空間的方法所以一般對時效性要求低的需求可以使用。
先放個phpspreadsheet官網提供的一個功能readCell,我們就可以利用這個功能來進行切割。
首先對excel檔案進行預讀,主要是獲取所有的工作表以及工作表下面的資料行數,這個階段readCell方法一直返回的都是false,我們只需要記錄readCell進來的工作表及資料行數。
然後就是對獲取到的記錄進行分析,確定每部分資料需要裝多少行原始excel的資料,需要注意的是為了避免內容混淆,不要講兩個工作表的內容切到一起。
最後就是迴圈分析的資料和再次利用readCell獲取每部分資料,注意每次讀取檔案後都要利用disconnectWorksheets方法清理phpspreadsheet的記憶體。
經過我自己的測試發現,利用該方法解析5M的excel檔案,平均只需要21M的記憶體就可以搞定!
<?php namespace CutExcel; require_once 'PhpSpreadsheet/autoload.php'; /** * 預讀過濾類 * @author wangyelou * @date 2018-07-30 */ class MyAheadreadFilter implements PhpOfficePhpSpreadsheetReaderIReadFilter { public $record = array(); private $lastRow = ''; public function readCell($column, $row, $worksheetName = '') { if (isset($this->record[$worksheetName]) ) { if ($this->lastRow != $row) { $this->record[$worksheetName] ++; $this->lastRow = $row; } } else { $this->record[$worksheetName] = 1; $this->lastRow = $row; } return false; } } /** * 解析過濾類 * @author wangyelou * @date 2018-07-30 */ class MyreadFilter implements PhpOfficePhpSpreadsheetReaderIReadFilter { public $startRow; public $endRow; public $worksheetName; public function readCell($column, $row, $worksheetName = '') { if ($worksheetName == $this->worksheetName && $row >= ($this->startRow+1) && $row <= ($this->endRow+1)) { return true; } return false; } } /** * 切割類 * @author wangyelou * @date 2018-07-30 */ class excelCut { public $cutNum = 5; public $returnType = 'Csv'; public $fileDir = '/tmp/'; public $log; /** * 切割字串 * @param $str * @return array|bool */ public function cutFromStr($str) { try { $filePath = '/tmp/' . time() . mt_rand(1000, 9000) . $this->returnType; file_put_contents($filePath, $str); if (file_exists($filePath)) { $result = $this->cutFromFile($filePath); unlink($filePath); return $result; } else { throw new Exception('檔案寫入錯誤'); } } catch (Exception $e) { $this->log = $e->getMessage(); return false; } } /** * 切割檔案 * @param $file * @return array|bool */ public function cutFromFile($file) { try { $cutRules = $this->readaheadFromFile($file); $dir = $this->getFileDir($file); $returnType = $this->returnType ? $this->returnType : 'Csv'; $results = array(); //初始化讀 $myFilter = new MyreadFilter(); $inputFileType = PhpOfficePhpSpreadsheetIOFactory::identify($file); $reader = PhpOfficePhpSpreadsheetIOFactory::createReader($inputFileType); $reader->setReadDataOnly(true); $reader->setReadFilter($myFilter); foreach ($cutRules as $sheetName => $rowIndexRange) { //讀 list($myFilter->startRow, $myFilter->endRow, $myFilter->worksheetName) = $rowIndexRange; $spreadsheetReader = $reader->load($file); $sheetData = $spreadsheetReader->setActiveSheetIndexByName($myFilter->worksheetName)->toArray(null, false, false, false); $realDatas = array_splice($sheetData, $myFilter->startRow, ($myFilter->endRow - $myFilter->startRow + 1)); $spreadsheetReader->disconnectWorksheets(); unset($sheetData); unset($spreadsheetReader); //寫 $saveFile = $dir . $sheetName . '.' . $returnType; $spreadsheetWriter = new PhpOfficePhpSpreadsheetSpreadsheet(); foreach ($realDatas as $rowIndex => $row) { foreach ($row as $colIndex => $col) { $spreadsheetWriter->getActiveSheet()->setCellValueByColumnAndRow($colIndex+1, $rowIndex+1, $col); } } $writer = PhpOfficePhpSpreadsheetIOFactory::createWriter($spreadsheetWriter, $returnType); $writer->save($saveFile); $spreadsheetWriter->disconnectWorksheets(); unset($spreadsheetWriter); $results[] = $saveFile; } return $results; } catch (Exception $e) { $this->log = $e->getMessage(); return false; } } /** * 預讀檔案 */ public function readaheadFromFile($file) { if (file_exists($file)) { //獲取統計資料 $myFilter = new MyAheadreadFilter(); $inputFileType = PhpOfficePhpSpreadsheetIOFactory::identify($file); $reader = PhpOfficePhpSpreadsheetIOFactory::createReader($inputFileType); $reader->setReadDataOnly(true); //唯讀資料 $reader->setReadFilter($myFilter); $spreadsheet = $reader->load($file); //$sheetData = $spreadsheet->getActiveSheet()->toArray(null, false, false, false); list($fileName,) = explode('.', basename($file)); $datas = array(); $averageNum = ceil(array_sum($myFilter->record) / $this->cutNum); foreach ($myFilter->record as $sheetName => $count) { for ($i=0; $i<ceil($count/$averageNum); $i++) { $datas[$fileName . '_' . $sheetName . '_' . $i] = array($i*$averageNum, ($i+1)*$averageNum-1, $sheetName); } } return $datas; } else { throw new Exception($file . ' not exists'); } } /** * 建立目錄 * @param $file * @return bool|string */ protected function getFileDir($file) { $baseName = basename($file); list($name) = explode('.', $baseName); $fullName = $name .'_'. time() . '_' . mt_rand(1000, 9999); $path = $this->fileDir . $fullName . '/'; mkdir($path, 0777); chmod($path, 0777); if (is_dir($path)) { return $path; } else { $this->log = "mkdir {$path} failed"; return false; } } }
相關教學:PHP視訊教學
以上就是PHP如何切割excel大檔案(附完整程式碼)的詳細內容,更多請關注TW511.COM其它相關文章!