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

gerar arquivo .xls pelo servidr web?


quinhosp

Pergunta

Boa noite!

Estou usando um código que consegui, ele funciona legal no localhost, pois gera o arquivo.xls para salvar, porém quando coloquei no servidor web o link para gerar o .xls tenta abrir uma página não existente.

Peço ajuda.

segue o código abaixo:

relatorioexcel.php

<?php

//Incluir a classe excelwriter

include("excelwriter.inc.php");

//Você pode colocar aqui o nome do arquivo que você deseja salvar.

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

if($excel==false){

echo $excel->error;

}

//Escreve o nome dos campos de uma tabela

$myArr=array('CODIGO','DESCRICAO','VALOR');

$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("banco", $conn);

}

$consulta = "select * from produtos order by descricao";

$resultado = mysql_query($consulta);

if($resultado==true){

while($linha = mysql_fetch_array($resultado)){

$myArr=array($linha['codigo'],$linha['descricao'],$linha['valor']);

$excel->writeLine($myArr);

}

}

$excel->close();

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

?>

classewriter.php

<?php

/*

* Class is used for save the data into microsoft excel format.

* It takes data into array or you can write data column vise.

*/

Class ExcelWriter{

var $fp=null;

var $error;

var $state="CLOSED";

var $newRow=false;

/*

* @Params : $file : file name of excel file to be created.

* @Return : On Success Valid File Pointer to file

* On Failure return false

*/

function ExcelWriter($file="",$bsc="CELLPAR"){

return $this->open($file);

}

/*

* @Params : $file : file name of excel file to be created.

* if you are using file name with directory i.e. test/myFile.xls

* then the directory must be existed on the system and have permissioned properly

* to write the file.

* @Return : On Success Valid File Pointer to file

* On Failure return false

*/

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;

}

/* @Params : Void

* @return : Void

* This function write the header of Excel file.

*/

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>";

}

/*

* @Params : $line_arr: An valid array

* @Return : Void

*/

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>");

}

/*

* @Params : Void

* @Return : Void

*/

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;

}

}

/*

* @Params : $value : Coloumn Value

* @Return : Void

*/

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

13 respostass a esta questão

Posts Recomendados

  • 0

Boa dia. consegui outro modo de fazer aqui, mas tá dando este erro, alguém sabe por que???? Desde já Grato.

Warning: mysql_num_fields(): supplied argument is not a valid MySQL result resource in /home/agencia propag/www/teste/propag/teste4.php on line 15

Warning: mysql_fetch_row(): supplied argument is not a valid MySQL result resource in /home/agenciapropag/www/teste/propag/teste4.php on line 49

segua abaixo o código:

teste4.php

<?php

include"conexao.php";

$select = "SELECT id , tipo , nome , rua , numero , bairro , cidade , estado , cep , dt_nascimento , telefone , celular , dt_cadastro , login , senha FROM id order by id";                
$export = mysql_query($select); 
$fields = mysql_num_fields($export); 
for($i = 0; $i < $fields; $i++) 
{  
    if( mysql_field_name($export, $i) == "id" )    
        $header .= "Código do Usuário"."\t";  
    elseif( mysql_field_name($export, $i) == "tipo" )    
        $header .= "Tipo de Usuário"."\t";  
    elseif( mysql_field_name($export, $i) == "nome" )    
        $header .= "Nome"."\t";  
    elseif( mysql_field_name($export, $i) == "rua" )    
        $header .= "Logradouro"."\t";  
    elseif( mysql_field_name($export, $i) == "numero" )    
        $header .= "Número"."\t";     
    elseif( mysql_field_name($export, $i) == "bairro" )    
        $header .= "Bairro"."\t";  
    elseif( mysql_field_name($export, $i) == "cidade" )    
        $header .= "Cidade"."\t";  
    elseif( mysql_field_name($export, $i) == "estado" )    
        $header .= "UF"."\t";  
    elseif( mysql_field_name($export, $i) == "dt_nascimento" )    
        $header .= "Data de Nascimento"."\t";    
    elseif( mysql_field_name($export, $i) == "telefone" )    
        $header .= "Telefone"."\t";  
    elseif ( mysql_field_name($export, $i) == "celular" )    
        $header .= "Celular"."\t";  
    elseif( mysql_field_name($export, $i) == "dt_cadastro" )    
        $header .= "Data do Cadastro"."\t";  
    elseif( mysql_field_name($export, $i) == "login" )    
        $header .= "login"."\t";       
    elseif ( mysql_field_name($export, $i) == "senha" )    
        $header .= "senha"."\t";         
    else     
        $header .= mysql_field_name($export, $i) . "\t"; 
    }
    while($row = mysql_fetch_row($export)) 
    {         
        $line = '';     
    foreach($row as $value) 
    {                                                  
        if((!isset($value)) OR ($value == "")) 
        {             
            $value = "\t";     
        } 
        else 
        {             
            $value = str_replace('"', '""', $value);             
            $value = '"' . $value . '"' . "\t";         
        }         
        $line .= $value;     
    }     
    $data .= trim($line)."\n";
    } 
    $data = str_replace("\r","",$data); 
    if ($data == "") 
    {     
        $data = "\n(0) Records Found!\n";                        
    }
?>

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

  • 0

Prezado,

Eu utilizo o script abaixo para salvar em excel o conteudo da pagina.

Faça um teste!

<?php
        header("Content-type: application/vnd.ms-excel");
        header("Content-type: application/force-download");
        header("Content-Disposition: attachment; filename=relatorio.xls");
        header("Pragma: no-cache");
                echo "<table>";
        echo "<tr><td>Teste</td></tr>";
        echo "<tr><td>Teste</td></tr>";
        echo "<tr><td>Teste</td></tr>";
        echo "</table>";
?>

Link para o comentário
Compartilhar em outros sites

  • 0

Romero valeu pela ajuda,

Mas olha só eu ajustei pro meu script aqui. A consulta foi realizada aparace a tebela mas não exporta para o excel.

Mostra os seguintes erros:

Warning: Cannot modify header information - headers already sent by (output started at /home/www/teste/propag/teste5.php:10) in /home/www/teste/propag/teste5.php on line 17

Warning: Cannot modify header information - headers already sent by (output started at /home/www/teste/propag/teste5.php:10) in /home/www/teste/propag/teste5.php on line 18

Warning: Cannot modify header information - headers already sent by (output started at /home/www/teste/propag/teste5.php:10) in /home/www/teste/propag/teste5.php on line 19

Warning: Cannot modify header information - headers already sent by (output started at /home/www/teste/propag/teste5.php:10) in /home/www/teste/propag/teste5.php on line 20

aqui está o código:

<?php

    include "conexao.php";
    
    $SQL = "SELECT * FROM usuario";
    $executa = mysql_query($SQL);

    header("Content-type: application/vnd.ms-excel");
    header("Content-type: application/force-download");
    header("Content-Disposition: attachment; filename=relatorio.xls");
    header("Pragma: no-cache");
        
    echo "<table border='1'>";
    echo "<tr>";
    echo "<td></td>";
    echo "<td>ID</td>";
    echo "<td>NOME</td>";
    echo "<td>TIPO</td>";
    echo "<td>LOGRADOURO</td>";
    echo "<td>NUMERO</td>";
    echo "<td>BAIRRO</td>";
    echo "<td>CIDADE</td>";
    echo "<td>ESTADO</td>";
    echo "<td>CEP</td>";
    echo "<td>DATA DE NASCIMENTO</td>";
    echo "<td>TELEFONE</td>";
    echo "<td>CELULAR</td>";
    echo "<td>DATA DO CADASTRO</td>";
    echo "<td>LOGIN</td>";
    echo "<td>SENHA</td>";
    echo "</tr>";

$i=1;
while ($rs = mysql_fetch_array($executa)){
echo "<tr>";
echo "<td>".$i."</td>";
echo "<td>" . $rs["id"] . "</td>";
echo "<td>" . $rs["nome"] . "</td>";
echo "<td>" . $rs["tipo"] . "</td>";
echo "<td>" . $rs["rua"] . "</td>";
echo "<td>" . $rs["numero"] . "</td>";
echo "<td>" . $rs["bairro"] . "</td>";
echo "<td>" . $rs["cidade"] . "</td>";
echo "<td>" . $rs["estado"] . "</td>";
echo "<td>" . $rs["cep"] . "</td>";
echo "<td>" . $rs["dt_nascimento"] . "</td>";
echo "<td>" . $rs["telefone"] . "</td>";
echo "<td>" . $rs["celular"] . "</td>";
echo "<td>" . $rs["cep"] . "</td>";
echo "<td>" . $rs["dt_cadastro"] . "</td>";
echo "<td>" . $rs["login"] . "</td>";
echo "<td>" . $rs["senha"] . "</td>";
echo "</tr>";
$i++;
}
echo "</table>"; 

?>

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

  • 0

Quando você inclui o script conexao.php, ele escreve alguma coisa na tela, o que gera este tipo de erro.

Tenta assim.

<?php
    header("Content-type: application/vnd.ms-excel");
    header("Content-type: application/force-download");
    header("Content-Disposition: attachment; filename=relatorio.xls");
    header("Pragma: no-cache");
        
    include "conexao.php";
    
    $SQL = "SELECT * FROM usuario";
    $executa = mysql_query($SQL);
    
    echo "<table border='1'>";
    echo "<tr>";
    echo "<td></td>";
    echo "<td>ID</td>";
    echo "<td>NOME</td>";
    echo "<td>TIPO</td>";
    echo "<td>LOGRADOURO</td>";
    echo "<td>NUMERO</td>";
    echo "<td>BAIRRO</td>";
    echo "<td>CIDADE</td>";
    echo "<td>ESTADO</td>";
    echo "<td>CEP</td>";
    echo "<td>DATA DE NASCIMENTO</td>";
    echo "<td>TELEFONE</td>";
    echo "<td>CELULAR</td>";
    echo "<td>DATA DO CADASTRO</td>";
    echo "<td>LOGIN</td>";
    echo "<td>SENHA</td>";
    echo "</tr>";

$i=1;
while ($rs = mysql_fetch_array($executa)){
echo "<tr>";
echo "<td>".$i."</td>";
echo "<td>" . $rs["id"] . "</td>";
echo "<td>" . $rs["nome"] . "</td>";
echo "<td>" . $rs["tipo"] . "</td>";
echo "<td>" . $rs["rua"] . "</td>";
echo "<td>" . $rs["numero"] . "</td>";
echo "<td>" . $rs["bairro"] . "</td>";
echo "<td>" . $rs["cidade"] . "</td>";
echo "<td>" . $rs["estado"] . "</td>";
echo "<td>" . $rs["cep"] . "</td>";
echo "<td>" . $rs["dt_nascimento"] . "</td>";
echo "<td>" . $rs["telefone"] . "</td>";
echo "<td>" . $rs["celular"] . "</td>";
echo "<td>" . $rs["cep"] . "</td>";
echo "<td>" . $rs["dt_cadastro"] . "</td>";
echo "<td>" . $rs["login"] . "</td>";
echo "<td>" . $rs["senha"] . "</td>";
echo "</tr>";
$i++;
}
echo "</table>";

?>

Link para o comentário
Compartilhar em outros sites

  • 0

não aconteceu nada, continua dando o mesmo erro.

olha só:

Warning: Cannot modify header information - headers already sent by (output started at /home/www/teste/propag/teste5.php:10) in /home/www/teste/propag/teste5.php on line 11

Warning: Cannot modify header information - headers already sent by (output started at /home/www/teste/propag/teste5.php:10) in /home/www/teste/propag/teste5.php on line 12

Warning: Cannot modify header information - headers already sent by (output started at /home/www/teste/propag/teste5.php:10) in /home/www/teste/propag/teste5.php on line 13

Warning: Cannot modify header information - headers already sent by (output started at /home/www/teste/propag/teste5.php:10) in /home/www/teste/propag/teste5.php on line 14

Link para o comentário
Compartilhar em outros sites

  • 0
Só a nivel de teste, na primeira linha acrescente ob_start();

*FIT*, boa noite!

Eu coloquei, legal saiu as mensagens de erro e gerou a planilha, porém não aparaceu nenhum dos dados do banco.

Sabe dizer porque a planilha não foi preenchida com os dados?

Grato,

Aqui tá o código:

<?php
ob_start(); 

include('conexao.php');

// Definimos o nome do arquivo que será exportado
$arquivo = 'planilha.xls';

$query = "SELECT * FROM usuario ORDER BY id";
$resultado = mysql_query ($query);

$html = '';
$html .= '<table border=1>';
$html .= '<tr>';
$html .= '<td colspan=5 align=center><b>CADASTRO DE FUNCIONÁRIOS</b></tr>';
$html .= '</tr>';
$html .= '<tr>';
$html .= '<td><b>ID</b></td>';
$html .= '<td><b>TIPO</b></td>';
$html .= '<td><b>NOME</b></td>';
$html .= '<td><b>LOGRADOURO</b></td>';
$html .= '<td><b>NUMERO</b></td>';
$html .= '<td><b>BAIRRO</b></td>';
$html .= '<td><b>CIDADE</b></td>';
$html .= '<td><b>UF</b></td>';
$html .= '<td><b>CEP</b></td>';
$html .= '<td><b>DT_NASCIMENTO</b></td>';
$html .= '<td><b>TELEFONE</b></td>';
$html .= '<td><b>CELULAR</b></td>';
$html .= '<td><b>DT_CADASTRO</b></td>';
$html .= '<td><b>LOGIN</b></td>';
$html .= '<td><b>SENHA</b></td>';
$html .= '</tr>';

while($campo = mysql_fetch_array ($resultado)){

$id = $campo ['id'];
$tipo = $campo ['tipo'];
$nome = $campo ['nome'];
$rua  = $campo ['rua'];
$numero = $campo ['numero'];
$bairro = $campo ['bairro'];
$cidade = $campo ['cidade'];
$estado = $campo ['estado'];
$cep    = $campo ['cep'];
$dt_nascimento = $campo ['dt_nascimento'];
$telefone = $campo ['telefone'];
$celular  = $campo ['celular'];
$dt_cadastro = $campo ['dt_cadastro'];
$login = $campo ['login'];
$senha = $campo ['senha'];

$html .= '<tr>';
$html .= '<td>' . $id . '</td>';
$html .= '<td>' . $tipo . '</td>';
$html .= '<td>' . $nome . '</td>';
$html .= '<td>' . $rua . '</td>';
$html .= '<td>' . $numero . '</td>';
$html .= '<td>' . $bairro . '</td>';
$html .= '<td>' . $cidade . '</td>';
$html .= '<td>' . $estado . '</td>';
$html .= '<td>' . $cep . '</td>';
$html .= '<td>' . $dt_nascimento . '</td>';
$html .= '<td>' . $telefone . '</td>';
$html .= '<td>' . $celular . '</td>';
$html .= '<td>' . $dt_cadastro . '</td>';
$html .= '<td>' . $login . '</td>';
$html .= '<td>' . $senha . '</td>';
$html .= '</tr>';
}
$html .= '</table>';

// Configurações header para forçar o download
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D,d M YH:i:s") . " GMT");
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
header("Content-type: application/x-msexcel");
header("Content-Disposition: attachment; filename=\"{$arquivo}\"" );
header("Content-Description: PHP Generated Data" );

// Envia o conteúdo do arquivo
echo $html;
exit;
?>

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

  • 0

Por favor, preciso de uma resposta...

O script gera uma planilha vazia, mas eu percebi no código que $arquivo = "planilha.xsl" e que passa este arquivo para o header

header("Content-Disposition: attachment; filename=\"{$arquivo}\"" );

, porém a consulta não é salva no arquivo, ou seja a consulta não va para planilha.

É isso mesmo, alguém pode me dar uma dica. grato....

<?php

ob_start();

include('conexao.php');

// Definimos o nome do arquivo que será exportado

$arquivo = 'planilha.xls';

$query = "SELECT * FROM usuario ORDER BY id";

$resultado = mysql_query($query) or die ("Erro: Não foi possível realizar a consulta");

$html = '';

$html .= '<table border=1>';

$html .= '<tr>';

$html .= '<td colspan=5 align=center><b>CADASTRO DE FUNCIONÁRIOS</b></tr>';

$html .= '</tr>';

$html .= '

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

  • 0

Ola, me Chamo Jefferson Oliveira, sou fundador do website www.programarearte.com.br

Fico muito feliz em saber que fui util na solucao da questao acima.

Qualque coisa se precisarem de mim estarei sempre em busca de ajudar no que for possivel.

Abracos a todos Vlw.

:rolleyes:

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
      152,2k
    • Posts
      652k
×
×
  • Criar Novo...