Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

WillowFranco

geração de .xls

Recommended Posts

Olá, amigos, tenho que gerar um xls de informações de uma página, e além de ser iniciante no PHP não fui eu que criei a pagina gostaria que me dessem alguma dica.

 

Segue o código da pagina.

 

 

<?php
include ("../../includes/include_geral.inc.php");
include ("../../includes/include_geral_II.inc.php");
$s_page_ocomon = "relatorio_geral.php";
session_register("s_page_ocomon");
if ($ok != 'Pesquisar') {
print testa_user($s_usuario,$s_nivel,$s_nivel_desc,4);
print "<html>";
print "<head><script language=\"JavaScript\" src=\"../../includes/javascript/calendar1.js\"></script>
<script type='text/javascript' src='../../GTI/js/jquery.js'></script>";?>
<script type="text/javascript">
$(document).ready(function(){
$("select[name=area]").change(function(){
$("select[name=problema]").html('<option value="0" >Carregando...</option>')
$.post('filtro.php', {sistema:$(this).val(), problema:true}, function(valor){
$("select[name=problema]").html(valor);
}
);
$("select[name=operador]").html('<option value="0" >Carregando...</option>')
$.post('filtro.php', {sistema:$(this).val(), operador:true}, function(valor){
$("select[name=operador]").html(valor);
}
);
});
});
</script><?
print "</head>";
print " <BR><BR>";
print " <B><center>::: Relatório de ocorrências :::</center></B><BR><BR>";
print " <FORM action='".$PHP_SELF."' method='post' name='form1'>";
print " <TABLE border='0' align='center' cellspacing='2' bgcolor=".BODY_COLOR.">";
print " <tr>";
print " <td bgcolor=".TD_COLOR.">Área Responsável:</td>";
print " <td><Select class='select' name='area' >";
print " <OPTION value=-1 selected>-->Todos<--</OPTION>";
$query="select * from sistemas where sis_status not in (0) order by sistema";
$resultado=mysql_query($query);
$linhas = mysql_num_rows($resultado);
while($row=mysql_fetch_array($resultado))
{
$sis_id=$row['sis_id'];
$sis_name=$row['sistema'];
print "<option value=$sis_id>$sis_name</option>";
} // while
print " </Select>";
print " </td>";
print " </tr>";
print " <TR>";
print " <TD bgcolor=".TD_COLOR.">Problema:</TD>";
print " <TD><SELECT class='select' NAME='problema'>";
print " <OPTION value=-1 selected>-->Todos<--</OPTION>";
$status = 1;
// $query_problema = "select * from problemas order by problema";
$query_problema = "select * from problemas where prob_status = 1 order by problema";
$resultado=mysql_query($query_problema);
$linhas=mysql_num_rows($resultado);
while($row=mysql_fetch_array($resultado))
{
$prob_id=$row['prob_id'];
$prob_name=$row['problema'];
print "<OPTION value=$prob_id> $prob_name </OPTION>";
} // while
print " </SELECT>";
print " </TD>";
print " </TR>";
print " <tr>";
print " <td bgcolor=".TD_COLOR.">Unidade:</td>";
print " <td><Select class='select' name='instituicao' size=1>";
print " <OPTION value=-1 selected>-->Todos<--</OPTION>";
$query="select * from instituicao where inst_status = 1 order by inst_nome";
$resultado=mysql_query($query);
$linhas = mysql_num_rows($resultado);
while($row=mysql_fetch_array($resultado))
{
$insti_id=$row['inst_cod'];
$insti_name=$row['inst_nome'];
print "<option value=$insti_id>$insti_name</option>";
} // while
print " </Select>";
print " </td>";
print " </tr>";
print " <tr>";
print " <td bgcolor=".TD_COLOR.">Orgão/Cliente</td>";
print " <td><select class='select' name='local' size=1> ";
print " <option value=-1 selected>-->Todos<--</option>";
$query="select * from localizacao where loc_status = 1 order by local";
$resultado=mysql_query($query);
while($row=mysql_fetch_array($resultado))
{
$local_id=$row['loc_id'];
$local_name=$row['local'];
print "<option value=$local_id>$local_name</option>";
}
print " </select>";
print " </td>";
print " </tr>";
print " <tr>";
print " <td bgcolor=".TD_COLOR.">Operador:</td>";
print " <td><select class='select' name='operador' size=1>";
print " <option value=-1 selected>-->Todos<--</option>";
$query="select * from usuarios where nivel not in (5) order by nome";
$resultado=mysql_query($query);
while($row=mysql_fetch_array($resultado))
{
//$operador=$row['login'];
print "<option value=$row[user_id]>$row[nome]</option>";
}
print " </select>";
print " </td>";
print " </tr>";
print " <tr>";
print " <td bgcolor=".TD_COLOR.">Data Inicial:</td>";
print " <td><INPUT name='d_ini' class='data'><a href=\"javascript:cal1.popup();\"><img src='../../includes/javascript/img/cal.gif' width='16' height='16' border='0' alt='Selecione a data'></a></td>";
print " </tr>";
print " <tr>";
print " <td bgcolor=".TD_COLOR.">Data Final:</td>";
print " <td><INPUT name='d_fim' class='data'><a href=\"javascript:cal2.popup();\"><img src='../../includes/javascript/img/cal.gif' width='16' height='16' border='0' alt='Selecione a data'></a></td>";
print " </tr>";
print " <tr>";
print " <td bgcolor=".TD_COLOR.">Data de:</td>";
print " <td><SELECT class='select' name='tipo_data'>";
print " <OPTION value=-1 selected>-->Todos<--</OPTION>";
print " <option value=1>Abertura</option>";
print " <option value=2>Encerramento</option>";
print " </SELECT>";
print " </td>";
print " </tr>";
print " <tr>";
print " <td bgcolor=".TD_COLOR.">Status:</td>";
print " <td><select class='select' name='status_oco'>";
print " <option value=-1 selected>-->Todos<--</option>";
print " <option value='Em aberto'>Em aberto</option>";
$query="select * from status order by status";
$resultado=mysql_query($query);
while($row=mysql_fetch_array($resultado))
{
$status_id=$row['stat_id'];
$status_name=$row['status'];
print "<option value=$status_id>$status_name</option>";
}
print " </select>";
print " </td>";
print " </tr>";
print " <tr>";
print " <td bgcolor=".TD_COLOR.">Ordena por:</td>";
print " <td><SELECT class='select' name='ordem' size=1>";
print " <option value='numero' selected>Número</option>";
print " <option value='problema'>Problema</option>";
print " <option value='sistema'>Área Responsável</option>";
print " <option value='instituicao'>Unidade</option>";
print " <option value='local'>Local</option>";
print " <option value='operador'>Operador</option>";
print " <option value='data_abertura'>Data</option>";
print " </SELECT>";
print " </td>";
print " </tr>";
print " <tr>";
print " <td bgcolor=".TD_COLOR.">Tipo de relatório:</td>";
print " <td><select class='select' name='saida' size=1>";
print " <option value=-1 selected>Normal</option>";
print " <option value=1>Relatório 1 linha</option>";
print " </select>";
print " </td>";
print " </tr>";
print " <tr>
<td colspan='2'><input type='checkbox' name='novaJanela' title='Selecione para que a saída seja em uma nova janela.'>Nova Janela (para impressão)
</td>
</tr>";
print " </TABLE><br>";
print " <TABLE align='center'>";
print " <tr>";
print " <TD>";
print " <input type='submit' value='Pesquisar' name='ok' onClick=\"submitForm();\">";//onclick='ok=sim'
print " </TD>";
print " <TD>";
print " <INPUT type='reset' value='Limpar campos' name='cancelar'>";
print " </TD>";
print " </tr>";
print " </TABLE>";
print " </form>";
print "</BODY>";
print "</html>";
?>
<script language="JavaScript">
// create calendar object(s) just after form tag closed
// specify form element as the only parameter (document.forms['formname'].elements['inputname']);
// note: you can have as many calendar objects as you need for your application
var cal1 = new calendar1(document.forms['form1'].elements['d_ini']);
cal1.year_scroll = true;
cal1.time_comp = false;
var cal2 = new calendar1(document.forms['form1'].elements['d_fim']);
cal2.year_scroll = true;
cal2.time_comp = false;
//-->
</script>
<?
} //if $ok!=Pesquisar
else //if $ok==Pesquisar
{
if ($saida==-1) //(modo normal)
{
print testa_user($s_usuario,$s_nivel,$s_nivel_desc,4);
}
$linhas=-1;
$hora_inicio = ' 00:00:00';
$hora_fim = ' 23:59:59'; // letra.campo_tab as apelido
$query = "select
o.numero, o.problema as oco_problema, p.problema,
o.sistema as oco_sistema, s.sistema,
o.instituicao as oco_instituicao, i.inst_nome,
o.local as oco_local, l.local,
o.operador, u.login, u.nome,
o.data_abertura, o.data_fechamento,
o.status, st.stat_id,st.status as nome_status
from
((ocorrencias as o left join sistemas as s on s.sis_id=o.sistema)
left join instituicao as i on o.instituicao=i.inst_cod),
problemas as p, localizacao as l, usuarios as u, `status` as st
where
o.problema=p.prob_id and o.local=l.loc_id and o.operador=u.user_id and o.status=st.stat_id";
if (!empty($problema) and ($problema != -1)) // variavel do select name
{
$query .= " and o.problema = $problema";
}
if (!empty($area) and ($area != -1)) // variavel do select name
{
$query .= " and o.sistema = $area";
}
if (!empty($instituicao) and ($instituicao != -1))
{
$query .= " and o.instituicao = $instituicao";
}
if (!empty($local) and ($local != -1))
{
$query .= " and o.local = $local";
}
if (!empty($operador) and ($operador != -1))
{
$query .= " and o.operador = '$operador' ";
}
if (!empty($status_oco) and ($status_oco != -1))
{
if ($status_oco == "Em aberto")
{
$query .= " and o.status not in (4,12) ";
}
else
{
$query .= " and o.status = $status_oco ";
}
}
if (empty($d_ini))
{
$d_ini = '01/03/2002';
}
if (empty($d_fim))
{
$hoje = getdate();
$mes = $hoje['mon'];
$dia = $hoje['mday'];
$ano = $hoje['year'];
$d_fim = "$dia/$mes/$ano";
}
//if (($d_ini < $d_fim) or ($d_ini == $d_fim))
//{
$d_ini = str_replace("-","/",$d_ini);
$d_fim = str_replace("-","/",$d_fim);
$d_ini_nova = converte_dma_para_amd($d_ini);
$d_fim_nova = converte_dma_para_amd($d_fim);
$d_ini_completa = $d_ini_nova.$hora_inicio;
$d_fim_completa = $d_fim_nova.$hora_fim;
switch ($tipo_data)
{
case -1:
$query .= " and o.data_abertura>='$d_ini_completa' and o.data_abertura<='$d_fim_completa'
and (o.data_fechamento>='$d_ini_completa' or o.data_fechamento is null)
and (o.data_fechamento<='$d_fim_completa' or o.data_fechamento is null)";
break;
case 1:
$query .= " and o.data_abertura>='$d_ini_completa' and o.data_abertura<='$d_fim_completa'";
break;
case 2:
$query .= " and (o.data_fechamento>='$d_ini_completa' or o.data_fechamento is null)
and (o.data_fechamento<='$d_fim_completa' or o.data_fechamento is null)";
break;
} // switch
$query .= " order by $ordem"; // print "<h2>$query</h2>";
$resultado = mysql_query($query); // print "<b>Query--></b> $query<br><br>";
$linhas = mysql_num_rows($resultado);
$data1 = explode("/","$d_ini"); // fatia a string $dat em pedados, usando / como referência
$d1 = $data1[0];
$m1 = $data1[1];
$y1 = $data1[2];
$data2 = explode("/","$d_fim"); // fatia a string $dat em pedados, usando / como referência
$d2 = $data2[0];
$m2 = $data2[1];
$y2 = $data2[2];
if(($d1 > $d2) and ($m1 >= $m2) and ($y1 >= $y2))
{
$aviso = "A data de início não pode ser maior<br> do que a data de fim. <br>Refaça sua pesquisa.";
$origem = 'javascript:history.back()';
session_register("aviso");
session_register("origem");
echo "<META HTTP-EQUIV=REFRESH CONTENT=\"0;URL=mensagem.php\">";
}}
if($d_ini_nova > $d_fim_nova)
{
$aviso = "A data de in�cio n�o pode ser maior<br> do que a data de fim. <br>Refa�a sua pesquisa.";
$origem = 'javascript:history.back()';
session_register("aviso");
session_register("origem");
echo "<META HTTP-EQUIV=REFRESH CONTENT=\"0;URL=mensagem.php\">";
}
switch($linhas)
{
case 0:
$aviso = "Nenhuma ocorrência foi localizada. <br>Refaça sua pesquisa.";
$origem = 'javascript:history.back()';
session_register("aviso");
session_register("origem");
echo "<META HTTP-EQUIV=REFRESH CONTENT=\"0;URL=mensagem.php\">";
break;
case 1:
$frase= "Foi encontrada somente <font color=red>1</font> ocorrência.";
break;
case -1:
default:
$frase="Foram encontradas <font color=red>$linhas</font> ocorrências.";
} // switch
switch($saida)
{
case -1:
$cor1=TD_COLOR;
print "<BR><BR><B>::: Relatório de ocorrências :::</B><BR><BR>";
print "<legend><FONT FACE=Arial, sans-serif><FONT SIZE=2 STYLE=font-size: 9pt>$frase</font></font></legend>";
print "";
print "<tr>";
print "<td bgcolor=$cor1 align=left width=48> <font size=2><b> Número <br></b></font></td>";
print "<td bgcolor=$cor1 align=left width=170><font size=2><b> Problema </b></font></td>";
print "<td bgcolor=$cor1 align=left width=150><font size=2><b> Área </b></font></td>";
print "<td bgcolor=$cor1 align=left width=90> <font size=2><b> Unidade </b></font></td>";
print "<td bgcolor=$cor1 align=left width=150><font size=2><b> Orgão/Cliente </b></font></td>";
print "<td bgcolor=$cor1 align=left width=50> <font size=2><b> Operador </b></font></td>";
print "<td bgcolor=$cor1 align=left width=50> <font size=2><b> Status </b></font></td>";
print "<td bgcolor=$cor1 align=left width=125><font size=2><b> Data Início </b></font></td>";
print "<td bgcolor=$cor1 align=left width=110><font size=2><b> Data Fim </b></font></td>";
print "<td bgcolor=$cor1 align=left width=110><font size=2><b> Dias em Aberto </b></font></td>";
print "</tr>";
$i=0;
$j=2;
print " <TD>";
print "<input type='submit' value='Baixar' name='ok' onClick=\"baixar_relatorio();\">";//onclick='ok=sim'
print " </TD>";
while ($row = mysql_fetch_array($resultado))
{
if ($j % 2)
{
$color = BODY_COLOR;
}
else
{
$color = white;
}
$j++;
print "";
print "<td width=48 align=left bgcolor=$color> <b><a href='mostra_consulta.php?numero=".$row['numero']."' target='_blank'><font color = blue>".$row['numero']." </font></b></a> </td>"; //nome q eu dei no select name=
print "<td width=170 align=left bgcolor=$color> ".$row['problema']."</td>";
print "<td width=150 align=left bgcolor=$color> ".$row['sistema']." </td>";
if ($row['inst_nome']=='')
{
print "<td width=90 align=center bgcolor=$color> - </td>";
}
else
{
print "<td width=90 align=left bgcolor=$color> " . $row['inst_nome'] . "</td>";
}
print "<td width=150 align=left bgcolor=$color> ".$row['local']."</td>";
print "<td width=50 align=left bgcolor=$color> ".$row['nome']."</td>";
print "<td width=50 align=left bgcolor=$color> ".$row['nome_status']."</td>";
print "<td width=125 align=left bgcolor=$color> ".converte_datacomhora($row['data_abertura'])."</td>";
if ($row['data_fechamento'] == null)
{
print "<td width=110 align=center bgcolor=$color> - </td>";
}
else
{
print "<td width=110 align=left bgcolor=$color> ".converte_datacomhora($row['data_fechamento'])."</td>";
}
$d_inicio = $row['data_abertura'];
$d_final = $row['data_fechamento'];
if ($row['data_fechamento'] == null){
$hoje = date("Y-m-d H:i:s");
$diff = date_diff_dias ($hoje,$d_inicio);
print "<td width=50 align=left bgcolor=$color> ".abs($diff)."</td>";
}
else
{
$diff = date_diff_dias ($d_final,$d_inicio);
print "<td width=50 align=left bgcolor=$color> ".abs($diff)."</td>";
}
print "";
} // while
print "";
print "";
break;
case 1:
$campos=array();
$campos[]="numero";
$campos[]="problema";
$campos[]="sistema";
$campos[]="inst_nome";
$campos[]="local";
$campos[]="operador";
$campos[]="data_abertura";
$campos[]="data_fechamento";
$cabs=array();
$cabs[]="Número";
$cabs[]="Problema";
$cabs[]="Área Responsável";
$cabs[]="Unidade";
$cabs[]="Local";
$cabs[]="Operador";
$cabs[]="Data Abertura";
$cabs[]="Data Encerramento";
$hoje=date('d/m/Y H:m');
gera_relatorio(1,$query,$campos,$cabs,"logo_unilasalle.gif","Centro de Informática", $hoje, "Relatório de Ocorrências");
break;
// switch
}//if $ok==Pesquisar
?>
<script type='text/javascript'>
<!--
function checar() {
var checado = false;
if (document.form1.novaJanela.checked){
checado = true;
//document.form1.target = "_blank";
} else {
checado = false;
//document.form1.target = "";
}
return checado;
}
window.setInterval("checar()",1000);
function submitForm()
{
if (checar() == true) {
document.form1.target = "_blank";
document.form1.submit();
} else {
document.form1.target = "";
document.form1.submit();
}
}
</script>

Compartilhar este post


Link para o post
Compartilhar em outros sites

Não da nem pra entender este código, mas se quer gerar .xls

 

Use a classe PHPExcel, é bem fácil a implementação.

 

ex.:

<?php 

$this->PhpExcel->createWorksheet();

// define table cells
$table = array(
    array('label' => __('Nome')),
    array('label' => __('Email')),
);

$this->PhpExcel->addTableHeader($table, array('name' => 'Cambria', 'bold' => true));

foreach ($documentos as $documento) {
    $this->PhpExcel->addTableRow(array(
        $documento['Cliente']['nome'],
        $documento['Cliente']['email']
    ));
}

// close table and output
$this->PhpExcel->addTableFooter()
    ->output('nome_arquivo.xls', 'Excel5');

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.