cakephp excel/csv导出组件

Adi*_*att 9 csv excel cakephp export

我想将Excel/CSV导出选项与我的CakePHP网站集成,任何有关可用组件或帮助程序的想法?

谢谢 !

Suh*_*man 19

此解决方案适用于CakePHP 2.0 ..您也可以将其集成到CakePHP 1.3中

步骤1:将以下文件作为Csv.php保存到您的app/View/Helper目录中

<?php
class CsvHelper extends AppHelper
{
var $delimiter = ',';
var $enclosure = '"';
var $filename = 'Export.csv';
var $line = array();
var $buffer;

function CsvHelper()
{
    $this->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);
}
}
?>
Run Code Online (Sandbox Code Playgroud)

第2步:将此助手添加到您的控制器:

var $helpers = array('Html', 'Form','Csv'); 
Run Code Online (Sandbox Code Playgroud)

步骤3:在控制器处创建方法"下载",例如.homes_controller.php

<?php
function download()
{
    $this->set('orders', $this->Order->find('all'));
    $this->layout = null;
    $this->autoLayout = false;
    Configure::write('debug', '0');
}
?>
Run Code Online (Sandbox Code Playgroud)

第4步:将此链接放在您必须下载CSV的页面上

<?php
echo $this->Html->link('Download',array('controller'=>'homes','action'=>'download'), array('target'=>'_blank'));
?>
Run Code Online (Sandbox Code Playgroud)

步骤:5(最后一步)

将此代码放在View/Homes/download.ctp上

<?php
 $line= $orders[0]['Order'];
 $this->CSV->addRow(array_keys($line));
 foreach ($orders as $order)
 {
      $line = $order['Order'];
       $this->CSV->addRow($line);
 }
 $filename='orders';
 echo  $this->CSV->render($filename);
?>
Run Code Online (Sandbox Code Playgroud)