cakephp excel/csv export component

后端 未结 4 1271
鱼传尺愫
鱼传尺愫 2020-12-09 00:15

I want to integrate Excel/CSV Export option with my CakePHP website, any idea about available components or helpers?

Thanks !

4条回答
  •  借酒劲吻你
    2020-12-09 00:48

    This solution is for CakePHP 2.0.. u can also integrate it in CakePHP 1.3

    Step 1: Save the following file as Csv.php into your app/View/Helper directory

    clear();
    }
    function clear() 
    {
        $this->line = array();
        $this->buffer = fopen('php://temp/maxmemory:'. (5*1024*1024), 'r+');
    }
    
    function addField($value) 
    {
        $this->line[] = $value;
    }
    
    function endRow() 
    {
        $this->addRow($this->line);
        $this->line = array();
    }
    
    function addRow($row) 
    {
        fputcsv($this->buffer, $row, $this->delimiter, $this->enclosure);
    }
    
    function renderHeaders() 
    {
        header('Content-Type: text/csv');
        header("Content-type:application/vnd.ms-excel");
        header("Content-disposition:attachment;filename=".$this->filename);
    }
    
    function setFilename($filename) 
    {
        $this->filename = $filename;
        if (strtolower(substr($this->filename, -4)) != '.csv') 
        {
            $this->filename .= '.csv';
        }
    }
    
    function render($outputHeaders = true, $to_encoding = null, $from_encoding ="auto") 
    {
        if ($outputHeaders) 
        {
            if (is_string($outputHeaders)) 
            {
                $this->setFilename($outputHeaders);
            }
            $this->renderHeaders();
        }
        rewind($this->buffer);
        $output = stream_get_contents($this->buffer);
    
        if ($to_encoding) 
        {
            $output = mb_convert_encoding($output, $to_encoding, $from_encoding);
        }
        return $this->output($output);
    }
    }
    ?>
    

    Step 2: Add this Helper to your controller:

    var $helpers = array('Html', 'Form','Csv'); 
    

    Step 3: create a method “download” at controller for eg. homes_controller.php

    set('orders', $this->Order->find('all'));
        $this->layout = null;
        $this->autoLayout = false;
        Configure::write('debug', '0');
    }
    ?>
    

    Step 4: put this link on page from where you have to download CSV

    Html->link('Download',array('controller'=>'homes','action'=>'download'), array('target'=>'_blank'));
    ?>
    

    Step: 5 (final step)

    Put this code on View/Homes/download.ctp

    CSV->addRow(array_keys($line));
     foreach ($orders as $order)
     {
          $line = $order['Order'];
           $this->CSV->addRow($line);
     }
     $filename='orders';
     echo  $this->CSV->render($filename);
    ?>
    

提交回复
热议问题