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 小时前
在Excel和WPS表格中批量删除数据区域的批注
excel·wps表格
我是zxb1 小时前
EasyExcel:快速读写Excel的工具类
数据库·oracle·excel
ONLYOFFICE2 小时前
【技术教程】如何将文档编辑器集成至用PHP编写的Web应用程序中
编辑器·php·onlyoffice
辣香牛肉面3 小时前
[Windows] 搜索文本2.6.2(从word、wps、excel、pdf和txt文件中查找文本的工具)
word·excel·wps·搜索文本
悠悠~飘3 小时前
php学习(第五天)
学习·php
ljf88385 小时前
Java导出复杂excel,自定义excel导出
java·开发语言·excel
tebukaopu1486 小时前
json文件转excel
json·excel
shizidushu6 小时前
How to work with merged cells in Excel with `openpyxl` in Python?
python·microsoft·excel·openpyxl
技术猿1887027835113 小时前
PHP 与 WebAssembly 的 “天然隔阂”
开发语言·php·wasm
小*-^-*九16 小时前
php 使用html 生成pdf word wkhtmltopdf 系列2
pdf·html·php