phpExcel导出大量数据出现内存溢出错误的解决方法

yipeiwu_com6年前PHP代码库

phpExcel将读取的单元格信息保存在内存中,我们可以通过

复制代码 代码如下:

PHPExcel_Settings::setCacheStorageMethod()

来设置不同的缓存方式,已达到降低内存消耗的目的!

1、将单元格数据序列化后保存在内存中

复制代码 代码如下:

PHPExcel_CachedObjectStorageFactory::cache_in_memory_serialized;

2、将单元格序列化后再进行Gzip压缩,然后保存在内存中

复制代码 代码如下:

PHPExcel_CachedObjectStorageFactory::cache_in_memory_gzip;

3、缓存在临时的磁盘文件中,速度可能会慢一些

复制代码 代码如下:

PHPExcel_CachedObjectStorageFactory::cache_to_discISAM;

4、保存在php://temp

复制代码 代码如下:

PHPExcel_CachedObjectStorageFactory::cache_to_phpTemp;

5、保存在memcache中

复制代码 代码如下:

PHPExcel_CachedObjectStorageFactory::cache_to_memcache

举例:

第4中方式:

 

复制代码 代码如下:

$cacheMethod = PHPExcel_CachedObjectStorageFactory:: cache_to_phpTemp; 
$cacheSettings = array( ' memoryCacheSize '  => '8MB' 
                ); 
PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);

第5种:

 

复制代码 代码如下:

$cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_to_memcache; 
$cacheSettings = array( 'memcacheServer'  => 'localhost', 
                        'memcachePort'    => 11211, 
                        'cacheTime'       => 600 
                      ); 
PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);

其它的方法

第一个方法,你可以考虑生成多个sheet的方式,不需要生成多个excel文件,根据你数据总量计算每个sheet导出多少行, 下面是PHPExcel生成多个sheet方法:

面是PHPExcel生成多个sheet方法:

复制代码 代码如下:

$sheet = $objPHPExcel->getActiveSheet();
$sheet->setCellValue('A1',$x); 
$sheet->setCellValue('B1',$y);

第二个方法,你可以考虑ajax来分批导出,不用每次刷新页面。

 

复制代码 代码如下:

<a href="#" id="export">export to Excel</a>
$('#export').click(function() { 
    $.ajax({ 
        url: "export.php",  
        data: getData(),  //这个地方你也可以在php里获取,一般读数据库 
        success: function(response){ 
            window.location.href = response.url; 
        } 
    }) 
});

复制代码 代码如下:

<?php
//export.php
$data = $_POST['data'];
$xls = new PHPExcel();
$xls->loadData($formattedData);
$xls->exportToFile('excel.xls');
$response = array(
'success' => true,
'url' => $url
);
header('Content-type: application/json');
echo json_encode($response);
?>

数据量很大的话,建议采用第二种方法,ajax来导出数据,上面方法简单给了个流程,具体你自己补充!

相关文章

PHP中对缓冲区的控制实现代码

大家在使用PHP的过程中不免要使用到header和setcookie两个函数,这两个函数会发送一段文件头信息给浏览器,但是如果在使用这两个函数之前已经有了任何输出(包括空输出,比如空格,...

php去除html标记的原生函数详解

     strip_tags 去掉 HTML 及 PHP 的标记。 语法: string strip_tags(string str); 传回值...

PHP XML数据解析代码

复制代码 代码如下: //xml string $xml_string="<?xml version='1.0'?> <users> <user id='3...

PHP类的静态(static)方法和静态(static)变量使用介绍

在php中,访问类的方法/变量有两种方法: 1. 创建对象$object = new Class(),然后使用”->”调用:$object->attribute/functi...

学习php设计模式 php实现模板方法模式

学习php设计模式 php实现模板方法模式

一、意图 定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。Template Method 使得子类可以在不改变一个算法的结构的情况下重定义该算法的某些特定的步骤【GOF95】 二、...