将大行导出到Excel文档,占用内存较小

时间:2011-10-10 17:00:04

标签: php memory-management memory-leaks propel phpexcel

我使用PHPExcel使用MySQL数据库中的数据创建Excel文档。我的脚本必须在512MB的RAM下执行,我遇到了麻烦,因为我的导出达到了200k记录:

  

PHP致命错误:允许的内存大小为......

如何使用PHPExcel在尽可能少的RAM中创建大型文档?

我目前的代码:

            // Autoload classes
    ProjectConfiguration::registerPHPExcel();


    $xls = new PHPExcel();
    $xls->setActiveSheetIndex(0);


    $i = 0; 
    $j = 2; 
            // Write the col names
    foreach ($columnas_excel as $columna) {
        $xls->getActiveSheet()->setCellValueByColumnAndRow($i,1,$columna);
        $xls->getActiveSheet()->getColumnDimensionByColumn($i)->setAutoSize(true);
        $i++;
    }


    // paginate the result from database
    $pager = new sfPropelPager('Antecedentes',50);
    $pager->setCriteria($query_personas);
    $pager->init();
    $last_page = $pager->getLastPage();

    //write the data to excel object
    for($pagina =1; $pagina <= $last_page; $pagina++) {
        $pager->setPage($pagina);
        $pager->init();
        foreach ($pager->getResults() as $persona) {
            $i = 0;
            foreach ($columnas_excel as $key_col => $columnas) {
                $xls->getActiveSheet()->setCellValueByColumnAndRow($i,$j,$persona->getByName($key_col, BasePeer::TYPE_PHPNAME));
                $i++;
            }
            $j++;
        }
    }

    // write the file to the disk
    $writer = new PHPExcel_Writer_Excel2007($xls);
    $filename = sfConfig::get('sf_upload_dir') . DIRECTORY_SEPARATOR . "$cache.listado_personas.xlsx";
    if (file_exists($filename)) {
        unlink($filename);
    }
    $writer->save($filename);

CSV版本:

// Write the col names to the file
$columnas_key = array_keys($columnas_excel);
file_put_contents($filename, implode(",", $columnas_excel) . "\n");

//write data to the file
for($pagina =1; $pagina <= $last_page; $pagina++) {                     
        $pager->setPage($pagina);
        $pager->init();
        foreach ($pager->getResults() as $persona) {
            $persona_arr = array();
            // make an array        
            foreach ($columnas_excel as $key_col => $columnas) {
                $persona_arr[] = $persona->getByName($key_col, BasePeer::TYPE_PHPNAME);                 
            }
            // append to the file
            file_put_contents($filename, implode(",", $persona_arr) . "\n", FILE_APPEND | LOCK_EX);             
        }
    }
Propel 向数据库发出请求时,

仍然存在RAM 的问题,就像Propel一样,每次发出新请求时都不释放RAM。我甚至尝试在每次迭代中创建和删除Pager对象

2 个答案:

答案 0 :(得分:1)

Propel在查询API中有formatters,您将能够编写此类代码:

<?php
$query = AntecedentesQuery::create()
           // Some ->filter()
           ;
$csv = $query->toCSV();

$csv包含一个CSV内容,您可以通过设置正确的mime类型来呈现。

答案 1 :(得分:0)

由于您似乎可以使用CSV,请尝试一次拉1条记录并将其附加到CSV。不要试图同时获得所有200k记录。

$cursor = mysql_query( $sqlToFetchData );    // get a MySql resource for your query
$fileHandle = fopen( 'data.csv', 'a');       // use 'a' for Append mode

while( $row = mysql_fetch_row( $cursor ) ){  // pull your data 1 record at a time
    fputcsv( $fileHandle, $row );            // append the record to the CSV file
}

fclose( $fileHandle );                       // clean up
mysql_close( $cursor );

我不确定如何将CSV转换为XLS文件,但希望这会让你顺利进行。