发布于 2014-12-16 06:37:06 | 516 次阅读 | 评论: 1 | 来源: 网友投递

这里有新鲜出炉的精品教程,程序狗速度看过来!

PHPExcel PHP类库

PHPExcel 是用来操作Office Excel 文档的一个PHP类库,它基于微软的OpenXML标准和PHP语言。可以使用它来读取、写入不同格式的电子表格,如 Excel (BIFF) .xls, Excel 2007 (OfficeOpenXML) .xlsx, CSV, Libre/OpenOffice Calc .ods, Gnumeric, PDF, HTML等等。


本文为大家讲解的是phpExcel导出大量数据出现内存溢出错误的解决方法,感兴趣的同学参考下。

PHPExcel 是用来操作Office Excel 文档的一个PHP类库,它基于微软的OpenXML标准和PHP语言。可以使用它来读取、写入不同格式的电子表格,如 Excel (BIFF) .xls, Excel 2007 (OfficeOpenXML) .xlsx, CSV, Libre/OpenOffice Calc .ods, Gnumeric, PDF, HTML等等。

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来导出数据,上面方法简单给了个流程,具体你自己补充!



最新网友评论  共有(1)条评论 发布评论 返回顶部
mxlojfp 发布于2016-02-12 00:28:34
支持(0)  反对(0)  回复

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务