Ir para conteúdo
Fórum Script Brasil
  • 0

(Resolvido) Exporta para (.xls) porém pula linhas antes de listar os d


O kriok

Pergunta

Olá gente....Tenho um script que complementa um pequeno sistema onde a função desse script é exportar os dados armazenados no bd para a extensão (.xls) , ele exporta normalmente sem grandes problemas...Mas tem um detalhe que está fazendo diferença... Ele pula a mesma quantidade de linhas que eu estou exportanto.....

Agradeço quem poder me ajudar....

Descrição : já no documento exportado (.xls).....Se eu exporto 3 linhas ele pula três linhas no arquivo já exportado .Sendo que meu bd tem milhares de linhas ,então esse erro não pode ocorrer, pois vai complicar quando todas as linhas estiverem inseridas .....

Exemplo:

Data - Cliente - CPF - Operação - Percentual - Prazo - Data de pagamento - Comissão - Órgão - Banco

PULA 1

PULA 2

PULA 3

Dados listados 1

Dados listados 2

Dados listados 3

Preciso que ele exporte normalmente sem pular essas linhas independente da quantidade .

Exemplo:

Data - Cliente - CPF - Operação - Percentual - Prazo - Data de pagamento - Comissão - Órgão - Banco

Dados listados 1

Dados listados 2

Dados listados 3

E assim por diante .....>

Seguem abaixo os arquivos

index.php


<?php
include "../validar_session.php";

include "../Config/config_sistema.php";

include("excelwriter.inc.php");


$excel=new ExcelWriter("excel3.xls");

if($excel==false){
echo $excel->error;
}

//Escreve o nome dos campos de uma tabela
$myArr=array('Data','Cliente','CPF','Operação','Percentual','Prazo','Data de pagamento','Comissão','Órgão','Banco');
$excel->writeLine($myArr);

//Seleciona os campos de uma tabela
$conn = mysql_connect("localhost", "usuario", "senha") or die ('Não foi possivel conectar ao banco de dados! Erro: ' . mysql_error());
if($conn)
{
mysql_select_db("nome-do-banco", $conn);
}
$consulta = "select * from dados_usuarios";
$resultado = mysql_query($consulta);
if($resultado==true){
while($linha = mysql_fetch_array($resultado)){
// QUANDO ALTERO ESTA PARTE NA HORA DA EXPORTAÇÃO ELE PULA A MESMA QUANTIDADE DE LINHAS QUE EU IMPLANTO .NESTE CASO 3 LINHAS//
$myArr1=array($linha['Lancamento1'],$linha['Cliente1'],$linha['CPF1'],$linha['OPER1'],$linha['Percent1'],$linha['PZ1'],$linha['Pgto1'],$linha['Comissao1'],$linha['ORGAO1'],$linha['BC1']);
$myArr2=array($linha['Lancamento2'],$linha['Cliente2'],$linha['CPF2'],$linha['OPER2'],$linha['Percent2'],$linha['PZ2'],$linha['Pgto2'],$linha['Comissao2'],$linha['ORGAO2'],$linha['BC2']);
$myArr3=array($linha['Lancamento3'],$linha['Cliente3'],$linha['CPF3'],$linha['OPER3'],$linha['Percent3'],$linha['PZ3'],$linha['Pgto3'],$linha['Comissao3'],$linha['ORGAO3'],$linha['BC3']);
$excel->writeLine($myArr1);
$excel->writeLine($myArr2);
$excel->writeLine($myArr3);
}
}


$excel->close();
echo "O arquivo foi salvo com sucesso. <a href=\"excel3.xls\">excel.xls</a>";

?>

[/codebox]

excelwriter.inc.php

[codebox]
<?php

Class ExcelWriter{

var $fp=null;
var $error;
var $state="CLOSED";
var $newRow=false;


function ExcelWriter($file="",$bsc="CELLPAR"){
return $this->open($file);
}


function open($file){
if($this->state!="CLOSED"){
$this->error="Error : Another file is opend .Close it to save the file";
return false;
}

if(!empty($file)){
$this->fp=@fopen($file,"w+");
}else{
$this->error="Usage : New ExcelWriter('fileName')";
return false;
}

if($this->fp==false){
$this->error="Error: Unable to open/create File.You may not have permmsion to write the file.";
return false;
}
$this->state="OPENED";
fwrite($this->fp,$this->GetHeader());
return $this->fp;
}

function close(){
if($this->state!="OPENED"){
$this->error="Error : Please open the file.";
return false;
}
if($this->newRow){
fwrite($this->fp,"</tr>");
$this->newRow=false;
}
fwrite($this->fp,$this->GetFooter());
fclose($this->fp);
$this->state="CLOSED";
return;
}


function GetHeader(){
$header = <<<EOH
<html xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns="http://www.w3.org/TR/REC-html40">

<head>
<meta http-equiv=Content-Type content="text/html; charset=us-ascii">
<meta name=ProgId content=Excel.Sheet>
<!--[if gte mso 9]><xml>
<o:DocumentProperties>
<o:LastAuthor>Sriram</o:LastAuthor>
<o:LastSaved>2005-01-02T07:46:23Z</o:LastSaved>
<o:Version>10.2625</o:Version>
</o:DocumentProperties>
<o:OfficeDocumentSettings>
<o:DownloadComponents/>
</o:OfficeDocumentSettings>
</xml><![endif]-->
<style>
<!--table
{mso-displayed-decimal-separator:"\.";
mso-displayed-thousand-separator:"\,";}
@page
{margin:1.0in .75in 1.0in .75in;
mso-header-margin:.5in;
mso-footer-margin:.5in;}
tr
{mso-height-source:auto;}
col
{mso-width-source:auto;}
br
{mso-data-placement:same-cell;}
.style0
{mso-number-format:General;
text-align:general;
vertical-align:bottom;
white-space:nowrap;
mso-rotate:0;
mso-background-source:auto;
mso-pattern:auto;
color:windowtext;
font-size:10.0pt;
font-weight:400;
font-style:normal;
text-decoration:none;
font-family:Arial;
mso-generic-font-family:auto;
mso-font-charset:0;
border:none;
mso-protection:locked visible;
mso-style-name:Normal;
mso-style-id:0;}
td
{mso-style-parent:style0;
padding-top:1px;
padding-right:1px;
padding-left:1px;
mso-ignore:padding;
color:windowtext;
font-size:10.0pt;
font-weight:400;
font-style:normal;
text-decoration:none;
font-family:Arial;
mso-generic-font-family:auto;
mso-font-charset:0;
mso-number-format:General;
text-align:general;
vertical-align:bottom;
border:none;
mso-background-source:auto;
mso-pattern:auto;
mso-protection:locked visible;
white-space:nowrap;
mso-rotate:0;}
.xl24
{mso-style-parent:style0;
white-space:normal;}
-->
</style>
<!--[if gte mso 9]><xml>
<x:ExcelWorkbook>
<x:ExcelWorksheets>
<x:ExcelWorksheet>
<x:Name>NOME_PLANILHA</x:Name>
<x:WorksheetOptions>
<x:Selected/>
<x:ProtectContents>False</x:ProtectContents>
<x:ProtectObjects>False</x:ProtectObjects>
<x:ProtectScenarios>False</x:ProtectScenarios>
</x:WorksheetOptions>
</x:ExcelWorksheet>
</x:ExcelWorksheets>
<x:WindowHeight>10005</x:WindowHeight>
<x:WindowWidth>10005</x:WindowWidth>
<x:WindowTopX>120</x:WindowTopX>
<x:WindowTopY>135</x:WindowTopY>
<x:ProtectStructure>False</x:ProtectStructure>
<x:ProtectWindows>False</x:ProtectWindows>
</x:ExcelWorkbook>
</xml><![endif]-->
</head>

<body link=blue vlink=purple>
<table x:str border=0 cellpadding=0 cellspacing=0 style='border-collapse: collapse;table-layout:fixed;'>
EOH;
return $header;
}

function GetFooter(){
return "</table></body></html>";
}


function writeLine($line_arr){
if($this->state!="OPENED"){
$this->error="Error : Please open the file.";
return false;
}
if(!is_array($line_arr)){
$this->error="Error : Argument is not valid. Supply an valid Array.";
return false;
}
fwrite($this->fp,"<tr>");
foreach($line_arr as $col)
fwrite($this->fp,"<td class=xl24 width=64 >$col</td>");
fwrite($this->fp,"</tr>");
}


function writeRow(){
if($this->state!="OPENED"){
$this->error="Error : Please open the file.";
return false;
}
if($this->newRow==false){
fwrite($this->fp,"<tr>");
}else{
fwrite($this->fp,"</tr><tr>");
$this->newRow=true;
}
}


function writeCol($value){
if($this->state!="OPENED"){
$this->error="Error : Please open the file.";
return false;
}
fwrite($this->fp,"<td class=xl24 width=64 >$value</td>");
}
}

?>


Link para o comentário
Compartilhar em outros sites

8 respostass a esta questão

Posts Recomendados

  • 0

Pô já tentei de tudo.Mas não consegui arrumar ..O erro deve ser até simples ..Mas eu não consegui arrumar..Será que ninguém sacou onde eu estou errado ali p/ poder me dar uma ajuda ? Quem poder me dar uma força agradeço...Valeu !

Link para o comentário
Compartilhar em outros sites

  • 0
//Escreve o nome dos campos de uma tabela

$myArr=array('Data','Cliente','CPF','Operação','Percentual','Prazo','Data de pagamento','Comissão','Órgão','Banco');

$excel->writeLine($myArr);

Pega esta linha e coloque dentro do while junto com os dados listados.

Ponha um IF nele para mostra-lo somente uma vez :)

Acredito que se colocá-lo para gravar junto com tudo, as quebras de linha somem.

Link para o comentário
Compartilhar em outros sites

  • 0
Aê Marcus Nunes ,estou engatinhando em php ainda hehe :blush: .. Tentei fazer parecido com o que lê as linhas da tabela do bd porém tirando os comandos "mysql_" .Só que certamente fiz errado pois ele está exportando só os títulos e repetindo várias vezes a sequência desses 10 títulos ....Mas acho q você matou o problema pois a debaixo tá assim e não tem essa quebra de linha...Tem como mostrar como ficaria ? Obrigado pelo interesse em ajudar amigo. :lol: Editado por O kriok
Link para o comentário
Compartilhar em outros sites

  • 0

Fiz um exemplo aqui, mas não testei.

Tenta aí... deve funcionar :)

<?php
include "../validar_session.php";

include "../Config/config_sistema.php";

include("excelwriter.inc.php");


$excel=new ExcelWriter("excel3.xls");

if($excel==false){
    echo $excel->error;
}


//Seleciona os campos de uma tabela
$conn = mysql_connect("localhost", "usuario", "senha") or die ('Não foi possivel conectar ao banco de dados! Erro: ' . mysql_error());
if($conn){
mysql_select_db("nome-do-banco", $conn);
}
$consulta = "select * from dados_usuarios";
$resultado = mysql_query($consulta);

if($resultado==true){

    $i = 1;
    while($linha = mysql_fetch_array($resultado)){
    
        if($i == 1){
            //Escreve o nome dos campos de uma tabela
            $myArr=array('Data','Cliente','CPF','Operação','Percentual','Prazo','Data de pagamento','Comissão','Órgão','Banco');
            $excel->writeLine($myArr);
        
            $i = 0;
        }
    
        // QUANDO ALTERO ESTA PARTE NA HORA DA EXPORTAÇÃO ELE PULA A MESMA QUANTIDADE DE LINHAS QUE EU IMPLANTO .NESTE CASO 3 LINHAS//
        $myArr1=array($linha['Lancamento1'],$linha['Cliente1'],$linha['CPF1'],$linha['OPER1'],$linha['Percent1'],$linha['PZ1'],$linha['Pgto1'],$linha['Comissao1'],$linha['ORGAO1'],$linha['BC1']);
        $myArr2=array($linha['Lancamento2'],$linha['Cliente2'],$linha['CPF2'],$linha['OPER2'],$linha['Percent2'],$linha['PZ2'],$linha['Pgto2'],$linha['Comissao2'],$linha['ORGAO2'],$linha['BC2']);
        $myArr3=array($linha['Lancamento3'],$linha['Cliente3'],$linha['CPF3'],$linha['OPER3'],$linha['Percent3'],$linha['PZ3'],$linha['Pgto3'],$linha['Comissao3'],$linha['ORGAO3'],$linha['BC3']);
        $excel->writeLine($myArr1);
        $excel->writeLine($myArr2);
        $excel->writeLine($myArr3);
    }

}


$excel->close();
echo "O arquivo foi salvo com sucesso. <a href=\"excel3.xls\">excel.xls</a>";
?>

Link para o comentário
Compartilhar em outros sites

  • 0
Fiz um exemplo aqui, mas não testei.

Tenta aí... deve funcionar :)

<?php
include "../validar_session.php";

include "../Config/config_sistema.php";

include("excelwriter.inc.php");


$excel=new ExcelWriter("excel3.xls");

if($excel==false){
    echo $excel->error;
}


//Seleciona os campos de uma tabela
$conn = mysql_connect("localhost", "usuario", "senha") or die ('Não foi possivel conectar ao banco de dados! Erro: ' . mysql_error());
if($conn){
mysql_select_db("nome-do-banco", $conn);
}
$consulta = "select * from dados_usuarios";
$resultado = mysql_query($consulta);

if($resultado==true){

    $i = 1;
    while($linha = mysql_fetch_array($resultado)){
    
        if($i == 1){
            //Escreve o nome dos campos de uma tabela
            $myArr=array('Data','Cliente','CPF','Operação','Percentual','Prazo','Data de pagamento','Comissão','Órgão','Banco');
            $excel->writeLine($myArr);
        
            $i = 0;
        }
    
        // QUANDO ALTERO ESTA PARTE NA HORA DA EXPORTAÇÃO ELE PULA A MESMA QUANTIDADE DE LINHAS QUE EU IMPLANTO .NESTE CASO 3 LINHAS//
        $myArr1=array($linha['Lancamento1'],$linha['Cliente1'],$linha['CPF1'],$linha['OPER1'],$linha['Percent1'],$linha['PZ1'],$linha['Pgto1'],$linha['Comissao1'],$linha['ORGAO1'],$linha['BC1']);
        $myArr2=array($linha['Lancamento2'],$linha['Cliente2'],$linha['CPF2'],$linha['OPER2'],$linha['Percent2'],$linha['PZ2'],$linha['Pgto2'],$linha['Comissao2'],$linha['ORGAO2'],$linha['BC2']);
        $myArr3=array($linha['Lancamento3'],$linha['Cliente3'],$linha['CPF3'],$linha['OPER3'],$linha['Percent3'],$linha['PZ3'],$linha['Pgto3'],$linha['Comissao3'],$linha['ORGAO3'],$linha['BC3']);
        $excel->writeLine($myArr1);
        $excel->writeLine($myArr2);
        $excel->writeLine($myArr3);
    }

}


$excel->close();
echo "O arquivo foi salvo com sucesso. <a href=\"excel3.xls\">excel.xls</a>";
?>

Pô não funcionou amigo ..Ele continua dando aquela quebra de linha ... Até me aventurei olhando o excelwriter.inc.php , p/ saber se tinha alguma configuração ali, mas não achei.

Link para o comentário
Compartilhar em outros sites

  • 0

hahaha

sério?

bom, tenta usar isso:

while($linha = mysql_fetch_array($resultado)){
    
   $myArr1=array($linha['Lancamento1'],$linha['Cliente1'],$linha['CPF1'],$linha['OPER1'],$linha['Percent1'],$linha['PZ1'],$linha['Pgto1'],$linha['Comissao1'],$linha['ORGAO1'],$linha['BC1']);
        $myArr2=array($linha['Lancamento2'],$linha['Cliente2'],$linha['CPF2'],$linha['OPER2'],$linha['Percent2'],$linha['PZ2'],$linha['Pgto2'],$linha['Comissao2'],$linha['ORGAO2'],$linha['BC2']);
     $myArr3=array($linha['Lancamento3'],$linha['Cliente3'],$linha['CPF3'],$linha['OPER3'],$linha['Percent3'],$linha['PZ3'],$linha['Pgto3'],$linha['Comissao3'],$linha['ORGAO3'],$linha['BC3']);
       

 if($i == 1){
                        $i = 0;
            $myArr=array('Data','Cliente','CPF','Operação','Percentual','Prazo','Data de pagamento','Comissão','Órgão','Banco');
            $excel->writeLine($myArr);}
                $excel->writeLine($myArr1);
        $excel->writeLine($myArr2);
        $excel->writeLine($myArr3);
    }

Editado por Marcus Nunes
Link para o comentário
Compartilhar em outros sites

  • 0
hahaha

sério?

bom, tenta usar isso:

while($linha = mysql_fetch_array($resultado)){
    
   $myArr1=array($linha['Lancamento1'],$linha['Cliente1'],$linha['CPF1'],$linha['OPER1'],$linha['Percent1'],$linha['PZ1'],$linha['Pgto1'],$linha['Comissao1'],$linha['ORGAO1'],$linha['BC1']);
        $myArr2=array($linha['Lancamento2'],$linha['Cliente2'],$linha['CPF2'],$linha['OPER2'],$linha['Percent2'],$linha['PZ2'],$linha['Pgto2'],$linha['Comissao2'],$linha['ORGAO2'],$linha['BC2']);
     $myArr3=array($linha['Lancamento3'],$linha['Cliente3'],$linha['CPF3'],$linha['OPER3'],$linha['Percent3'],$linha['PZ3'],$linha['Pgto3'],$linha['Comissao3'],$linha['ORGAO3'],$linha['BC3']);
       

 if($i == 1){
                        $i = 0;
            $myArr=array('Data','Cliente','CPF','Operação','Percentual','Prazo','Data de pagamento','Comissão','Órgão','Banco');
            $excel->writeLine($myArr);}
                $excel->writeLine($myArr1);
        $excel->writeLine($myArr2);
        $excel->writeLine($myArr3);
    }
Pô amigo seguinte o problema não era esse descobri que eu estava errado na hora de colocar aqui "mysql_query" ,aí mudei o while($linha = mysql_fetch_array($resultado )) para while($linha = mysql_fetch_array($login)) ...Tá funcionando que é uma maravilha ..hehe ...Walew pela ajuda brother... :) ((((((((( RESOLVIDO ))))))))))
$login  =   mysql_query("select * from dados_usuarios where Nome = '$login_usuario'");
   $resultado = mysql_query($consulta);
   if($resultado==true){
      while($linha = mysql_fetch_array($login)){

Editado por O kriok
Link para o comentário
Compartilhar em outros sites

Participe da discussão

Você pode postar agora e se registrar depois. Se você já tem uma conta, acesse agora para postar com sua conta.

Visitante
Responder esta pergunta...

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emoticons são permitidos.

×   Seu link foi incorporado automaticamente.   Exibir como um link em vez disso

×   Seu conteúdo anterior foi restaurado.   Limpar Editor

×   Você não pode colar imagens diretamente. Carregar ou inserir imagens do URL.



  • Estatísticas dos Fóruns

    • Tópicos
      152k
    • Posts
      651,8k
×
×
  • Criar Novo...