PHP 使用Spreadsheet写excel缓存导致内存不断增加

这里写自定义目录标题

问题描述

新增了 Spreadsheet 用于写 excle 文件。

从网上查找一些实例后,封装成 createExcelFormData 函数如下:

php 复制代码
/**
 * @brief                   按照指定的键,将 array2(关联数组) 合并到 array1(关联数组)
 * @param mixed $data       数据数组,其中第一行表示行头
 * @param mixed $path       输出路径
 * @param mixed $filename   表格名称
 * @param mixed $key        0=成功,其他=失败
 * @return                  array(关联数组)
 */
function createExcelFormData($data, $path, $filename)
{
    if(!mkDirs($path)){
        return -1;
    }
 
    // Create new Spreadsheet object
    $spreadsheet = new PhpOffice\PhpSpreadsheet\Spreadsheet();
 
    // Set active sheet
    $sheet = $spreadsheet->getActiveSheet();
 
    // Add data rows
    $sheet->fromArray($data, null, 'A1');
 
    // Save Excel file
    $writer = new PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
    $writer->save($path . "/" . $filename);
}

自测发现,在每次执行一次导出日志写excel后,内存不断增加如下:


问题解决

经分析和查找一些文档后发现:Spreadsheet写excel表格的是存在缓存机制,缓存在函数执行完成后并不会释放。

对于一些需要清空缓存的场景,需要增加清空缓存语句:PhpOffice\PhpSpreadsheet\Settings::getCache()->clear();

修改后的createExcelFormData函数如下:

php 复制代码
/**
 * @brief                   按照指定的键,将 array2(关联数组) 合并到 array1(关联数组)
 * @param mixed $data       数据数组,其中第一行表示行头
 * @param mixed $path       输出路径
 * @param mixed $filename   表格名称
 * @param mixed $key        0=成功,其他=失败
 * @return                  array(关联数组)
 */
function createExcelFormData($data, $path, $filename)
{
    if(!mkDirs($path)){
        return -1;
    }
 
    // Create new Spreadsheet object
    $spreadsheet = new PhpOffice\PhpSpreadsheet\Spreadsheet();
 
    // Set active sheet
    $sheet = $spreadsheet->getActiveSheet();
 
    // Add data rows
    $sheet->fromArray($data, null, 'A1');
 
    // Save Excel file
    $writer = new PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
    $writer->save($path . "/" . $filename);
 
    // 清空和释放缓存
    PhpOffice\PhpSpreadsheet\Settings::getCache()->clear(); // 一定要释放cache,否则会导致内存不断增长!!!
    unset($spreadsheet);
    unset($writer);
}
相关推荐
济南壹软网络科技有限公司1 天前
综合社交服务平台的技术架构与实践:构建高可用、多端覆盖的互动生态
uni-app·php·开源源码·陪玩陪聊h5
好学且牛逼的马1 天前
【手写Mybatis | version0.0.3 附带源码 项目文档】
开发语言·php·mybatis
Q_Q5110082851 天前
python+springboot+django/flask基于深度学习的旅游推荐系统
spring boot·python·django·flask·node.js·php
Q_Q5110082851 天前
python+django/flask+vue基于深度学习的家庭用电量预测模型研究系统
spring boot·python·django·flask·node.js·php
Q_Q19632884751 天前
python+django/flask+vue的智能房价分析与预测系统
spring boot·python·django·flask·node.js·php
梦想的旅途21 天前
非官方接口下企业微信外部群主动交互:数据传输稳定性优化方案摘要
开发语言·php
Q_Q5110082851 天前
python+springboot+django/flask基于数据挖掘的高考志愿推荐系统
spring boot·python·django·flask·node.js·php
Q_Q5110082851 天前
python+django/flask+vue基于深度学习的图书推荐系统
spring boot·python·django·flask·node.js·php
ohoy1 天前
easypoi 自定义样式 学生-分数红绿颜色设置
excel
ranchor6661 天前
excel+pandas使用str.contains() 的典型例子
excel·pandas