Problems with Phpexcel columns

Asked

Viewed 812 times

1

I started to perform the development on my system to generate a file . xls in a very dynamic way. Where you receive the data from a page via POST, and are saved in variables, follow the code:

<?php
$tabela = $_POST['txttabela'];
$p_colunas = $_POST['chkcolunas'];

$qtdColunas = count($p_colunas);
$condicao = "email IS NOT NULL";



// Incluimos a classe PHPExcel
include  '../../componentes/plugins/PHPExcel/Classes/PHPExcel.php';

// Instanciamos a classe
$objPHPExcel = new PHPExcel();



 // Podemos definir as propriedades do documento
$objPHPExcel->getProperties()->setCreator("Floricultura Filippi")
        ->setLastModifiedBy("Floricultura Filippi   ")
        ->setTitle("Floricultura Filippi - Pedidos")
        ->setSubject("Floricultura Filippi - Pedidos - Exportação")
        ->setDescription("Dados Exportados do Banco de Dados");

// Adicionamos um estilo de A1 até D1 
$objPHPExcel->getActiveSheet()->getStyle('A1:D1')->applyFromArray(
        array('fill' => array(
                'type' => PHPExcel_Style_Fill::FILL_SOLID,
                'color' => array('rgb' => 'E0EEEE')
            ),
        )
);


if($p_colunas==""){
    ?>
    <script>
        alert("Você tem que selecionar ao menos uma coluna");
    </script>
    <?php
}else{
    $sel_sintaxe = "SELECT "; # adiciona o INSERT  e a sua tabela, deixando o parateses aberto para concatenar no proximo $adc_sintaxe

    $row = 1;
    $col = 0;
    for($i=0; $i<$qtdColunas; $i++){
         $p_colunas[$i];

         $sel_sintaxe.= $p_colunas[$i].", ";

        // Criamos as colunas
        $objPHPExcel->setActiveSheetIndex(0)
        ->setCellValueByColumnAndRow($col, $row, $p_colunas[$i]);

        $col++;

    }

    $sel_sintaxe = substr($sel_sintaxe, 0, -2);  #Essa funcao ela devolve somente oq interessa, tirando  a ultima virgula e espaco do INSERT, que no caso daria erro
    $sel_sintaxe .= " FROM ".$tabela."";

    $RdNull = $_POST['rdNull'];
    $RdDescAsc = $_POST['rdDescAsc'];
    if(isset($_POST['txtlimite'])){
        $txtLimite = $_POST['txtlimite'];
    }

    if($RdNull || $RdDescAsc || isset($txtLimite)){

        if($RdNull=="nao"){
            $sel_sintaxe .=" WHERE ";
            for($i=0; $i<$qtdColunas; $i++){
                 $p_colunas[$i];

                  $sel_sintaxe.= $p_colunas[$i]." OR  ";

            }
            $sel_sintaxe = substr($sel_sintaxe, 0, -5);
            $sel_sintaxe.= " IS NOT NULL";
            $sel_sintaxe;
        }
        if($RdNull=="sim"){
            $sel_sintaxe .=" WHERE ";
            for($i=0; $i<$qtdColunas; $i++){
                 $p_colunas[$i];

                  $sel_sintaxe.= $p_colunas[$i]." OR  ";

            }
            $sel_sintaxe = substr($sel_sintaxe, 0, -5);
            $sel_sintaxe.= " IS NULL";

            $sel_sintaxe;
        }

        if($RdDescAsc){

            $sel_sintaxe.= " ORDER BY $tabela.id $RdDescAsc";
            $sel_sintaxe;
        }

        if(isset($txtLimite)){

            $sel_sintaxe.= " LIMIT $txtLimite";
            echo $sel_sintaxe;
        }
    }


    echo $sel_sintaxe;
    $sql_sel_tabela_preparado = $conexaobd->prepare($sel_sintaxe);
    $sql_sel_tabela_preparado->execute();




// Alterando o tamanho da fonte
$objPHPExcel->getActiveSheet()->getStyle('A2:C1')->getFont()->setSize(14);

// Define a planilha ativa para o PHPExcel operar
$objPHPExcel->setActiveSheetIndex(0);

// Define o título da planilha 
$objPHPExcel->getActiveSheet()->setTitle('Planilha de Credeciamento 1');

// Define a largura das colunas de modo automático
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setAutoSize(true);

// Exemplo de preenchimento de dados de maneira dinâmica, a partir de um resultado do banco de dados por exemplo.
$linha = 3;
while($sql_sel_tabela_dados = $sql_sel_tabela_preparado->fetch()){
    $col = 0;
    for($i=0; $i<$qtdColunas; $i++){
            $colunaInver = $p_colunas[$i];
            //$colNumber = PHPExcel_Cell::columnIndexFromString($XX);
            echo $colString = PHPExcel_Cell::stringFromColumnIndex($col);

            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue($colString. $linha, $sql_sel_tabela_dados[$colunaInver]);

                echo $linha++;
                $col++;

        }

}

// Salva  o arquivo 
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save("ff_pedidos.com.br.xls");
//$objWriter->save('php://output');
}
?>

When generating Excel, every three data, should break line and stay one thing under the other see how this getting: Exemplo do .xls

I wish it was one thing underneath the other, well organized someone can tell me my mistake?

1 answer

1


If I understand correctly, the problem is that you are not re-setting the value $col with each new line, so it keeps increasing indefinitely.

Setar $col = 0 each new data line must solve:

while($sql_sel_tabela_dados = $sql_sel_tabela_preparado->fetch()){
    $col = 0; // migrado para dentro do while   
    for($i=0; $i<$qtdColunas; $i++){
  • That’s exactly what I’m gonna check out

  • Almost worked, look how I edited the code with its modifications and the image also, but the data are not on each other :( . How could I put one thing on each other’s side. Thank you so far!

  • I managed to solve by throwing the $line++ out of the for and putting inside the while

  • mass, that’s what I was going to suggest!

  • Thanks Ricardo, I appreciate your help, it’s so much new detail that I passed blank in the smallest details!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.