在CRUD系统中使用过滤器并导出excel

时间:2017-05-17 10:05:33

标签: php codeigniter phpexcel

我正在研究CRM系统,在其中我需要在excel中创建报告,我需要选择在excel中导出数据库的所有数据,还需要用户选项来过滤他们想要的数据并导出只有这些选项。

我已经将显示和搜索方法分开并且使用相同的视图来查看内容(总计或已过滤)我也有Excel的导出方法,但我只能导出整个数据库(没有过滤器)

我最初的想法是让我的视图发送到get_excel方法显示的内容然后该方法只生成excel本身,但我不知道如何将该数据数组从视图传递到现在控制器上的方法。

以下是我使用的代码:

控制方法:

Index显示视图的所有数据库数据

function index()
{
    $this->template->set('title', 'Lista de Produtos');
    $config = array(
        "base_url" => base_url('produtos/p'),
        "per_page" => 9,
        "num_links" => 3,
        "uri_segment" => 3,
        "total_rows" => $this->model->countAll(),
        "full_tag_open" => "<ul class='pagination'>",
        "full_tag_close" => "</ul>",
        "first_link" => FALSE,
        "last_link" => FALSE,
        "first_tag_open" => "<li>",
        "first_tag_close" => "</li>",
        "prev_link" => "Anterior",
        "prev_tag_open" => "<li class='prev'>",
        "prev_tag_close" => "</li>",
        "next_link" => "Próxima",
        "next_tag_open" => "<li class='next'>",
        "next_tag_close" => "</li>",
        "last_tag_open" => "<li>",
        "last_tag_close" => "</li>",
        "cur_tag_open" => "<li class='active'><a href='#'>",
        "cur_tag_close" => "</a></li>",
        "num_tag_open" => "<li>",
        "num_tag_close" => "</li>"
        );

    $this->pagination->initialize($config);

    $data['pagination'] = $this->pagination->create_links();

    $offset = ($this->uri->segment(3)) ? $this->uri->segment(3):0;

    $data['produtos'] = $this->model->listar('pcod','asc', $config['per_page'],$offset);
    $this->template->load('layout', 'produtos_lista.phtml', $data);
}

Searh:

使用过滤器仅显示请求的数据

public function pesquisar() {

    $this->template->set('title', 'Resultado');

    $data['pagination'] = "";

    $data['produtos'] = $this->model->search();

    $this->template->load('layout', 'produtos_lista.phtml', $data);
}

Get_excel:

在excel中生成报告

function  get_excel(){
    //$this->load->library('PHPExcel');
    $contator = 1;
    $arquivo = './planilhas/relatorio.xlsx';
    $planilha = $this->phpexcel;

    $planilha->setActiveSheetIndex(0)->setCellValue('A1','Codigo');
    $planilha->setActiveSheetIndex(0)->setCellValue('B1','Nome');
    $planilha->setActiveSheetIndex(0)->setCellValue('C1','Descrição');

    $data['produtos'] = $this->model->listar();
    //echo json_encode($data['produtos']);
    //die('eieeiie');


    foreach($data['produtos'] as $linha) {
        $contator++;
        $planilha->setActiveSheetIndex(0)->setCellValue('A'.$contator, $linha->pnome);
        $planilha->setActiveSheetIndex(0)->setCellValue('B'.$contator, $linha->descricao);
        $planilha->setActiveSheetIndex(0)->setCellValue('C'.$contator, $linha->pcod);
    }

    $planilha->getActiveSheet()->setTitle('planilha 1');

    $objgravar = PHPExcel_IOFactory::createWriter($planilha, 'Excel2007');
    $objgravar->save($arquivo);

    $this->session->set_flashdata('mensagem', "<div class='alert alert-warning'> exportação salva com sucesso</div>");
            redirect('produtos');

}

最后我的观点:

<body>

<div class="row" >
    <form action="/sistema/produtos/pesquisar" method="post">
        <div class="col-sm-9">
            <div class="form-group">
                <input name="search" class="form-control" id="search" type="text"
                    placeholder="Filtrar produto " value="<?php echo $view_termo??null ;?>">  
                    <span class="input-group-btn"></span>
            </div>
        </div>

        <div class="col-sm-1">
            <button class="btn btn-primary pull-left" type="submit">Filtrar</button>
        </div>

    </form>

    <div class="col-sm-2">
        <a data-toggle="modal" data-target="#new_produto" class="btn btn-primary ">Adicionar Produto</a>
    </div>

</div>

<div id="list" class="row">
    <div class="table-responsive col-md-12">
        <table class="table table-striped" cellspacing="0" cellpadding="0">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Nome</th>
                    <th>Descrição</th>
                    <th class="actions">Ações</th>
                </tr>
            </thead>

            <tbody>

                <?php foreach ( $produtos as $produto ) {?>
                    <tr>
                        <td><?php echo $produto->pcod; ?></td>    
                        <td><?php echo $produto->pnome; ?></td>    
                        <td><?php echo $produto->descricao; ?></td>
                        <td class="actions">
                            <a title="Editar" class="btn btn-warning btn-xs" href="<?php echo base_url() . 'produtos/editar/' . $produto->pcod; ?>"> Editar</a>
                            <a title="Deletar" class="btn btn-danger btn-xs" href="<?php echo base_url() . 'produtos/deletar/' . $produto->pcod; ?>" onclick="return confirm('Confirma a exclusão deste registro?')">Deletar</a>
                        </td>       

                    </tr>               

                <?php } ?>
            </tbody>
        </table>
            <h3><?php echo $this->session->flashdata('mensagem');?></h3>
    </div>
</div>  
<div class="row">
    <div class="col-sm-4" >
      <?php echo $pagination; ?>
    </div>

    <div class="col-sm-2">
        <a class="btn btn-primary" href="<?php echo base_url().'produtos/get_excel'?>">Export</a>
    </div>

</div>

1 个答案:

答案 0 :(得分:0)

使用javascript获取html内容并使用一些插件转换为csv更容易。如果你使用后端,需要处理值,取消设置一些变量,表格可能会混乱,有时很难操纵大数组。

内容的可视化/过滤也会更容易,因为只设置了一些&display; none&#39;在CSS中将做到这一点。我知道你标记了php / codeigniter / phpexcel,但是我已经做了许多需要这些功能的项目,而且我知道如果内容迅速升级为大数据,那将是多么痛苦。

如果你想采取我的方法:

Stack的一些答案会推荐来自kunalbabre的table2CSV,但该插件已经停止/损坏,所以我建议使用Github的excellentexport,它很简单并且有许多方法,其中一个显示进入README的git存储库:

module Users
  class RegistrationsController < Devise::RegistrationsController

用户想要过滤视图的列,只需用javascript标识并将display:none / visibility:hidden视为您希望的,您也可以通过使用javascript解析或使用{{3}之类的插件轻松订购列内容放入你的桌子:

<table id="datatable">
    <tr>
        <td>100</td> <td>200</td> <td>300</td>
    </tr>
    <tr>
        <td>400</td> <td>500</td> <td>600</td>
    </tr>
</table>

<a download="somedata.xls" href="#" onclick="return ExcellentExport.excel(this, 'datatable', 'Sheet Name Here');">Export to Excel</a>
<a download="somedata.csv" href="#" onclick="return ExcellentExport.csv(this, 'datatable');">Export to CSV</a>

表格的功能是如此可扩展,想要转换为CSV的用户如此沉迷于Excel功能,我强烈建议尝试在javascript中实现。