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);
}
相关推荐
审判长烧鸡8 小时前
【GO VS PHP】之 指针/引用传递
go·php·指针·引用传递
xingpanvip9 小时前
星盘接口开发文档:星相日历接口指南
android·开发语言·前端·css·php·lua
前端技术11 小时前
03_网络层与IP编址:理解网络寻址的核心逻辑
服务器·网络·php
niucloud-admin12 小时前
PHP V6 单商户常见问题——配置了伪静态仍提示接口请求错误,请检查VIE_APP_BASE_URL参数配置或者伪静态配置
php
Ether IC Verifier13 小时前
OSI网络七层协议详细介绍
服务器·网络·网络协议·计算机网络·php·dpu
这儿有一堆花13 小时前
住宅代理(Residential Proxy)技术指南
开发语言·数据库·php
Eiceblue14 小时前
使用 C# 将 Excel 转换为 Markdown 表格(含批量转换示例)
开发语言·c#·excel
Java面试题总结14 小时前
使用 Python 设置 Excel 数据验证
开发语言·python·excel
niucloud-admin14 小时前
PHP V6 单商户常见问题——升级提示mkdir()处理方案
php