Foros del Web » Programando para Internet » PHP »

[URGENTE]Crear Un Archivo Excel Dinamico Con Php

Estas en el tema de [URGENTE]Crear Un Archivo Excel Dinamico Con Php en el foro de PHP en Foros del Web. BUENO ESTOY REALIZANDO UNA APLICAION WEB LA CUAL DEBE DE GENERAR UN REPORTE EN EXCEL BUENO HE EN CONTRADO UNA PHP QUE PUEDE SOLUCIONAR ESTO ...
  #1 (permalink)  
Antiguo 04/02/2008, 14:47
Avatar de wladtepes  
Fecha de Ingreso: febrero-2008
Mensajes: 140
Antigüedad: 16 años, 2 meses
Puntos: 0
Exclamación [URGENTE]Crear Un Archivo Excel Dinamico Con Php

BUENO ESTOY REALIZANDO UNA APLICAION WEB LA CUAL DEBE DE GENERAR UN REPORTE EN EXCEL BUENO HE EN CONTRADO UNA PHP QUE PUEDE SOLUCIONAR ESTO PERO TIENE UN ERROR QUE NO ESTIENDO

HAY LES DEJO EL CODIGO

Código PHP:
      require_once("excel.php");
  
      require_once(
"excel-ext.php");
   
      
// Consultamos los datos desde MySQL

      
$conEmp mysql_connect("localhost""userDB""passDB");

      
mysql_select_db("sampleDB"$conEmp);
 
      
$queEmp "SELECT nombre, direccion, telefono FROM empresa";

      
$resEmp mysql_query($queEmp$conEmp) or die(mysql_error());

      
$totEmp mysql_num_rows($resEmp);

      
// Creamos el array con los datos

      
while($datatmp mysql_fetch_assoc($resEmp)) {

          
$data[] = $datatmp;

      }

      
// Generamos el Excel 

      
createExcel("excel-mysql.xls"$data);

      exit; 

Código PHP:
excel_ext.php

<?php
function createExcel($filename$arrydata) {
    
$excelfile "xlsfile://tmp/".$filename;  
    
$fp fopen($excelfile"wb");  
    if (!
is_resource($fp)) {  
        die(
"Error al crear $excelfile");  
    }  
    
fwrite($fpserialize($arrydata));  
    
fclose($fp);
    
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=\"" $filename "\"" );
    
readfile($excelfile);  
}
?>


Código PHP:

excel.php

<?php

class xlsStream
{
    
/* private */
    
var $position 0;          // stream pointer
    
var $mode "rb";           // default stream open mode
    
var $xlsfilename null;    // stream name
    
var $fp null;             // internal stream pointer to physical file
    
var $buffer null;         // internal write buffer
    
var $endian "unknown";    // little | unknown | big endian mode
    
var $bin = array(
        
"big" => "v",
        
"little" => "s",
        
"unknown" => "s",
    );

    
/**
     * detect server endian mode
     * thanks to Charles Turner for picking this one up
     * @access    private
     * @params    void
     * @returns    void
     * @see        http://www.phpdig.net/ref/rn45re877.html
     */
    
function _detect()
    {
        
// A hex number that may represent 'abyz'
        
$abyz 0x6162797A;

        
// Convert $abyz to a binary string containing 32 bits
        // Do the conversion the way that the system architecture wants to
        
switch (pack ('L'$abyz))
        {
            
// Compare the value to the same value converted in a Little-Endian fashion
            
case pack ('V'$abyz):
                
$this->endian "little";
                break;

            
// Compare the value to the same value converted in a Big-Endian fashion
            
case pack ('N'$abyz):
                
$this->endian "big";
                break;

            default:
                
$this->endian "unknown";
                break;
        }
    }

    
/**
     * called by fopen() to the stream
     * @param   (string)    $path           file path
     * @param   (string)    $mode           stream open mode
     * @param   (int)       $options        stream options (STREAM_USE_PATH |
     *                                      STREAM_REPORT_ERRORS)
     * @param   (string)    $opened_path    stream opened path
     */
    
function stream_open($path$mode$options, &$opened_path)
    {
        
$url parse_url($path);
        
$this->xlsfilename '/' $url['host'] . $url['path'];
        
$this->position 0;
        
$this->mode $mode;

        
$this->_detect();    // detect endian mode

        //@TODO: test for invalid mode and trigger error if required

        // open underlying resource
        
$this->fp = @fopen($this->xlsfilename$this->mode);
        if (
is_resource($this->fp))
        {
            
// empty the buffer
            
$this->buffer "";

            if (
preg_match("/^w|x/"$this->mode))
            {
                
// write an Excel stream header
                
$str pack(str_repeat($this->bin[$this->endian], 6), 0x8090x80x00x100x00x0);
                
fwrite($this->fp$str);
                
$opened_path $this->xlsfilename;
                
$this->position strlen($str);
            }
        }
        return 
is_resource($this->fp);
    }

    
/**
     * read the underlying stream resource (automatically called by fread/fgets)
     * @todo    modify this to convert an excel stream to an array
     * @param   (int)       $byte_count     number of bytes to read (in 8192 byte blocks)
     */
    
function stream_read($byte_count)
    {
        if (
is_resource($this->fp) && !feof($this->fp))
        {
            
$data .= fread($this->fp$byte_count);
            
$this->position strlen($data);
        }
        return 
$data;
    }

    
/**
     * called automatically by an fwrite() to the stream
     * @param   (string)    $data           serialized array data string
     *                                      representing a tabular worksheet
     */
    
function stream_write($data)
    {
        
// buffer the data
        
$this->buffer .= $data;
        
$bufsize strlen($data);
        return 
$bufsize;
    }

    
/**
     * pseudo write function to manipulate the data
     * stream before writing it
     * modify this to suit your data array
     * @access  private
     * @param   (array)     $data           associative array representing
     *                                      a tabular worksheet
     */
    
function _xls_stream_write($data)
    {
        if (
is_array($data) && !empty($data))
        {
            
$row 0;
            foreach (
array_values($data) as $_data)
            {
                if (
is_array($_data) && !empty($_data))
                {
                    if (
$row == 0)
                    {
                        
// write the column headers
                        
foreach (array_keys($_data) as $col => $val)
                        {
                            
// next line intentionally commented out
                            // since we don't want a warning about the
                            // extra bytes written
                            // $size += $this->write($row, $col, $val);
                            
$this->_xlsWriteCell($row$col$val);
                        }
                        
$row++;
                    }

                    foreach (
array_values($_data) as $col => $val)
                    {
                        
$size += $this->_xlsWriteCell($row$col$val);
                    }
                    
$row++;
                }
            }
        }
        return 
$size;
    }

    
/**
     * Excel worksheet cell insertion
     * (single-worksheet supported only)
     * @access  private
     * @param   (int)       $row            worksheet row number (0...65536)
     * @param   (int)       $col            worksheet column number (0..255)
     * @param   (mixed)     $val            worksheet row number
     */
    
function _xlsWriteCell($row$col$val)
    {
        if (
is_float($val) || is_int($val))
        {
            
// doubles, floats, integers
            
$str  pack(str_repeat($this->bin[$this->endian], 5), 0x20314$row$col0x0);
            
$str .= pack("d"$val);
        }
        else
        {
            
// everything else is treated as a string
            
$l    strlen($val);
            
$str  pack(str_repeat($this->bin[$this->endian], 6), 0x204$l$row$col0x0$l);
            
$str .= $val;
        }
        
fwrite($this->fp$str);
        
$this->position += strlen($str);
        return 
strlen($str);
    }

    
/**
     * called by an fclose() on the stream
     */
    
function stream_close()
    {
        if (
preg_match("/^w|x/"$this->mode))
        {
            
// flush the buffer
            
$bufsize $this->_xls_stream_write(unserialize($this->buffer));

            
// ...and empty it
            
$this->buffer null;

            
// write the xls EOF
            
$str pack(str_repeat($this->bin[$this->endian], 2), 0x0A0x00);
            
$this->position += strlen($str);
            
fwrite($this->fp$str);
        }

        
// ...and close the internal stream
        
return fclose($this->fp);
    }

    function 
stream_eof()
    {
        
$eof true;
        if (
is_resource($this->fp))
        {
            
$eof feof($this->fp);
        }
        return 
$eof;
    }
}

stream_wrapper_register("xlsfile""xlsStream")
    or die(
"Failed to register protocol: xlsfile");
?>


LO ENCONTRE EN :http://blog.unijimpe.net/generar-excel-con-php/

EL ERROR QUE ME GENERA ES Error al crear xlsfile://tmp/excel-mysql.xls

de antemano les doy las gracias

Última edición por wladtepes; 05/02/2008 a las 08:28 Razón: NO HAY RESPUESTA CLARA
  #2 (permalink)  
Antiguo 04/02/2008, 16:49
 
Fecha de Ingreso: noviembre-2007
Mensajes: 203
Antigüedad: 16 años, 4 meses
Puntos: 0
Re: Crear Un Archivo Excel Dinamico Con Php

hola, necesitas una extension que ahora no me acuerdo como se llama pero con xampp viene instalada, si tienes la aplicacion web en un hosting contacta a tu proveedor para que te la pongan (el que paga manda, no lo olvides).
  #3 (permalink)  
Antiguo 05/02/2008, 06:33
Avatar de wladtepes  
Fecha de Ingreso: febrero-2008
Mensajes: 140
Antigüedad: 16 años, 2 meses
Puntos: 0
Re: Crear Un Archivo Excel Dinamico Con Php

Bueno Gracias Pero Estoy Haciendo Pruebas De Forma Local, Pero Si Te Acuerdas De La Extension Te Estari Muy Agradecido
  #4 (permalink)  
Antiguo 05/02/2008, 13:55
Avatar de wladtepes  
Fecha de Ingreso: febrero-2008
Mensajes: 140
Antigüedad: 16 años, 2 meses
Puntos: 0
Re: [URGENTE]Crear Un Archivo Excel Dinamico Con Php

bueno lo arregle

los cambios deben de realizarse en el archivo creaexcel.php


$excelfile = “xlsfile://tmp/”.$filename;
por
$excelfile = “xlsfile://”.$filename;


y el excelphp.php
$this->xlsfilename = ‘/’ . $url[’host’] . $url[’path’];

por

$this->xlsfilename = $url[’host’] . $url[’path’];

crea el archivo excel en el escritorio de forma dinamica


extraido de http://blog.unijimpe.net/generar-excel-con-php/

adios:
  #5 (permalink)  
Antiguo 06/02/2008, 14:03
 
Fecha de Ingreso: noviembre-2007
Mensajes: 203
Antigüedad: 16 años, 4 meses
Puntos: 0
Re: [URGENTE]Crear Un Archivo Excel Dinamico Con Php

rebice el xampp (que incluye la extension) y dice que es PEAR.
  #6 (permalink)  
Antiguo 06/02/2008, 14:39
 
Fecha de Ingreso: abril-2007
Mensajes: 140
Antigüedad: 17 años
Puntos: 3
Re: [URGENTE]Crear Un Archivo Excel Dinamico Con Php

simplemente quiero aportar esto: xampp es una libreria genia, pero a veces me sirvio mas esto:
Arriba del tab <html> se pone:
<?php
header("Content-Type: application/vnd.ms-excel");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
?>
Y , te cuento que lo que yo hice fue una tabla que en lugar de salir en pantalla con el browser sale en Excel (no recuerdo si con el browser o no). Y no se si decirte que lo que no este en la tabla sale en la planilla Excell (creo que si), pero se puede probar. Suerte !!!!!!!!!!
  #7 (permalink)  
Antiguo 07/02/2008, 12:57
 
Fecha de Ingreso: noviembre-2007
Mensajes: 203
Antigüedad: 16 años, 4 meses
Puntos: 0
Re: [URGENTE]Crear Un Archivo Excel Dinamico Con Php

arriba de <html>???
para un arhcivo de excel?
bueno se como trabaja el sistema de crear archivos de excel pero pabloturchi tiene razon, primero hay que enviar los header() para que se genere el archivo de excel correctamente.
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta

SíEste tema le ha gustado a 1 personas




La zona horaria es GMT -6. Ahora son las 11:52.