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

phpExcel将读取的单元格信息保存在内存中,咱们能够经过php

代码以下:
PHPExcel_Settings::setCacheStorageMethod()

来设置不一样的缓存方式,已达到下降内存消耗的目的!ajax

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

代码以下:

PHPExcel_CachedObjectStorageFactory::cache_in_memory_serialized;

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

代码以下:

PHPExcel_CachedObjectStorageFactory::cache_in_memory_gzip;

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

代码以下:

PHPExcel_CachedObjectStorageFactory::cache_to_discISAM;

四、保存在php://tempapp

代码以下:

PHPExcel_CachedObjectStorageFactory::cache_to_phpTemp;

五、保存在memcache中url

代码以下:

PHPExcel_CachedObjectStorageFactory::cache_to_memcache

举例:excel

第4种方式:code

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

第5种:orm

代码以下:
$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来导出数据,上面方法简单给了个流程,具体你本身补充!

相关文章
相关标签/搜索