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);
}
相关推荐
JaguarJack1 天前
告别 Laravel 缓慢的 Blade!Livewire Blaze 来了,为你的 Laravel 性能提速
后端·php·laravel
郑州光合科技余经理1 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
QQ5110082852 天前
python+springboot+django/flask的校园资料分享系统
spring boot·python·django·flask·node.js·php
WeiXin_DZbishe2 天前
基于django在线音乐数据采集的设计与实现-计算机毕设 附源码 22647
javascript·spring boot·mysql·django·node.js·php·html5
LAM LAB2 天前
【VBA】Excel指定单元格范围内字体设置样式,处理导出课表单元格
excel·vba
在这habit之下2 天前
Keepalived学习总结
excel
longxiangam2 天前
Composer 私有仓库搭建
php·composer
上海云盾-高防顾问2 天前
DNS异常怎么办?快速排查+解决指南
开发语言·php
Youngchatgpt2 天前
如何在 Excel 中使用 ChatGPT:自动化任务和编写公式
人工智能·chatgpt·自动化·excel
开开心心就好2 天前
安卓开源应用,超时提醒紧急人护独居安全
windows·决策树·计算机视觉·pdf·计算机外设·excel·动态规划