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);
}
相关推荐
XR12345678819 小时前
工厂车间无线网络方案对比:AGV漫游哪家强?
开发语言·php
現実君21 小时前
【硬件进阶】AD22上位替换JLEDA教程
开发语言·php
ms365copilot21 小时前
算数据+做图表,Copilot Excel公式+图表联动
excel·copilot
宁小法1 天前
php - request_terminate_timeout解释
php·php-fpm·进程终止·请求终止超时
ms365copilot1 天前
在Copilot聊天中添加Word、Excel 和 PowerPoint 代理
word·excel·copilot
Smilecoc1 天前
Excel之Subtotal:功能强大的统计函数
excel
郝亚军1 天前
FE1.1S-BQFN24BT可以指定IP端口吗?
开发语言·php
WA内核拾荒者1 天前
WhatsApp 富媒体消息(图片/视频)的发送优化与压缩策略
php·音视频·媒体
用户0332126663671 天前
使用 Python 在 Excel 中添加或删除批注
python·excel
WA内核拾荒者1 天前
WhatsApp 多语言 AI 对话的语言模型选择与本地化适配
人工智能·语言模型·php