PHPExcel大文件块级别读取 速度快 减少占用资源

复制代码
  /**
     * 读取excel转换成数组
     *
     * @param string $excelFile 文件路径
     * @param int $startRow 开始读取的行数
     * @param int $endRow 结束读取的行数
     * @return array
     */
    private function readFromExcel($excelFile, $startRow = 1, $endRow = 100) {
        include_once './Core/Common/PHPExcel.php';
        include_once './Core/Common/PHPExcelReadFilter.php';

        $excelType = PHPExcel_IOFactory::identify($excelFile);
        $excelReader = \PHPExcel_IOFactory::createReader($excelType);

        if(strtoupper($excelType) == 'CSV') {
            $excelReader->setInputEncoding('GBK');
        }

        if ($startRow && $endRow) {
            $excelFilter           = new PHPExcelReadFilter();
            $excelFilter->startRow = $startRow;
            $excelFilter->endRow   = $endRow;
            $excelReader->setReadFilter($excelFilter);
        }

        $phpexcel    = $excelReader->load($excelFile);
        $activeSheet = $phpexcel->getActiveSheet();

        $highestColumn      = $activeSheet->getHighestColumn(); //最后列数所对应的字母,例如第1行就是A
        $highestColumnIndex = \PHPExcel_Cell::columnIndexFromString($highestColumn); //总列数

        $data = array();
        for ($row = $startRow; $row <= $endRow; $row++) {
            for ($col = 0; $col < $highestColumnIndex; $col++) {
                $data[$row][] = (string) $activeSheet->getCellByColumnAndRow($col, $row)->getValue();
            }
            if(implode($data[$row], '') == '') {
                unset($data[$row]);
            }
        }
        return $data;
    }
复制代码
复制代码
$rowSize = 200; 
$startRow = 2;//从第二行开始读取
$endRow = $rowSize;
$excel_orders = array();
while (true) {
  $excel_orders = $this->readFromExcel(dirname(dirname(HOME_PATH)).'/Upload/'.$newname, $startRow, $endRow);
    if(empty($excel_orders)) {
          break;
    }
    $startRow = $endRow + 1;
    $endRow = $endRow + $rowSize;
}
复制代码
复制代码
/**
 * 读取excel过滤器类 单独文件
 */
class PHPExcelReadFilter implements PHPExcel_Reader_IReadFilter {

    public $startRow = 1;
    public $endRow;

    public function readCell($column, $row, $worksheetName = '') {
        if (!$this->endRow) {
            return true;
        }
        
        if ($row >= $this->startRow && $row <= $this->endRow) {
            return true;
        }

        return false;
    }

}
复制代码

 

描述:用户导入订单数据,但用户导入8k左右的数据之后,PHP开始爆红了。

查阅部分资料得知,是由于PHPExcel的类读取,如果使用

$PHPExcel = $PHPReader->load($newfilename);

load的方式读取文件的话,是把文件中的全部内容读出并储存在内存中,再读取内容的话,就是直接从内存中读取,极其消耗资源。

而以上代码片段实现的效果就是我需要那块(n-m行)的内容,我只读去那部分的内容,不会加载整个文件。

最后,使用完变量,可以进行 $a = null; / unset($a); 进行释放资源。

祝工作顺利!

posted @   露娜喵喵  阅读(10904)  评论(2编辑  收藏  举报
编辑推荐:
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
阅读排行:
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 推荐几款开源且免费的 .NET MAUI 组件库
· 实操Deepseek接入个人知识库
· 易语言 —— 开山篇
· Trae初体验
点击右上角即可分享
微信分享提示