Foros del Web » Programando para Internet » PHP »

Una ayudita con importar mysql a excel

Estas en el tema de Una ayudita con importar mysql a excel en el foro de PHP en Foros del Web. Hola a todos, antes que nada les agradezco una vez mas todas las atenciones que han tenido conmigo, me han sacado de muchas dudas y ...
  #1 (permalink)  
Antiguo 18/12/2009, 12:28
 
Fecha de Ingreso: julio-2009
Mensajes: 63
Antigüedad: 14 años, 9 meses
Puntos: 0
Una ayudita con importar mysql a excel

Hola a todos, antes que nada les agradezco una vez mas todas las atenciones que han tenido conmigo, me han sacado de muchas dudas y me han ayudado a echar a andar un proyecto que tengo para mi trabajo.

Mi problema ahora consiste en que tengo creado un formulario por medio del cual alimento una base de datos mysql, hasta ahi todo bien, tengo tambien una pagina de resultados con un codigo de paginacion, por que esta base de datos es alimientada dirariamente con aproximadamente 30 o 40 registros vamos bien, la cosa es que buscando en san google encontre un codigo para importar los datos de esa db mysql a excel por medio de un codigo php y la cuestion es que en mi servidor local si me funciona, pero la pagina web de mi trabajo la tengo hosteada y cuando subo esos archivos y cambio los parametros respectivos aun asi no me funciona, no c si tendra algo que ver el hecho de que uso php 4 por que de hecho en una pagina lei algo de que tenia que ver con PEAR, pero bueno les plasmo el codigo que utilizo y les agradeceria infinitamente si me echaran una mano o las dos por que realmente tengo prioridad en resolver este problema.

Por ultimo les pongo el codigo de error que me marca mysql y quiero comentar para que no hayan malos entendidos que revise todas las faq's correspondientes a este tema, pero la verdad es que no todas tienen respuestas satisfactorias y las otras clases de php hacen algo similar pero esta hace justamente lo que yo requiero y por otro lado vamos descartando los permisos de lectura y escritura por que mi host si me los permite.

De antemano les agradezco la atencion prestada y les deseo un excelente dia !!!

ERROR MYSQL: Warning: fopen(xlsfile://Layout_Mexico.xls) [function.fopen]: failed to open stream: "xlsstream::stream_open" call failed in C:\Inetpub\vhosts\miservidor.com.mx\httpdocs\Carpe ta\subcarpeta\excel-ext.php on line 5
Error al crear $excelfile

Los scripts que utilizo los pongo abajo, por que el post es larguisimo.
  #2 (permalink)  
Antiguo 18/12/2009, 12:33
 
Fecha de Ingreso: julio-2009
Mensajes: 63
Antigüedad: 14 años, 9 meses
Puntos: 0
Respuesta: Una ayudita con importar mysql a excel

Bueno este es mi codigo por que creo que editando tampoco puedo escribir tantas palabras.

Código PHP:
Ver original
  1. array.php
  2.  
  3. <?php
  4. require_once("excel.php");  
  5. require_once("excel-ext.php");
  6.  
  7. $assoc = array(  
  8.             array("Nombre"=>"Mattias", "IQ"=>250),  
  9.             array("Nombre"=>"Tony", "IQ"=>100),  
  10.             array("Nombre"=>"Peter", "IQ"=>100),  
  11.             array("Nombre"=>"Edvard", "IQ"=>100)
  12.          );  
  13.    
  14. createExcel("excel-mysql.xls", $data);
  15. ?>

Código PHP:
Ver original
  1. excel.php
  2.  
  3. <?php
  4. /**
  5.  * MS-Excel stream handler
  6.  * This class read/writes a data stream directly
  7.  * from/to a Microsoft Excel spreadsheet
  8.  * opened with the xlsfile:// protocol
  9.  * This is used to export associative array data directly to MS-Excel
  10.  * @requires    PHP 4 >= 4.3.2
  11.  * @author      Ignatius Teo            <[email protected]>
  12.  * @copyright   (C)2004 act28.com       <http://act28.com>
  13.  * @version     0.3
  14.  * @date        20 Jan 2005
  15.  * $Id: excel.php,v 1.3 2005/01/20 09:58:58 Owner Exp $
  16.  */
  17. class xlsStream
  18. {
  19.     /* private */
  20.     var $position = 0;          // stream pointer
  21.     var $mode = "rb";           // default stream open mode
  22.     var $xlsfilename = null;    // stream name
  23.     var $fp = null;             // internal stream pointer to physical file
  24.     var $buffer = null;         // internal write buffer
  25.     var $endian = "unknown";    // little | unknown | big endian mode
  26.     var $bin = array(
  27.         "big" => "v",
  28.         "little" => "s",
  29.         "unknown" => "s",
  30.     );
  31.  
  32.     /**
  33.      * detect server endian mode
  34.      * thanks to Charles Turner for picking this one up
  35.      * @access  private
  36.      * @params  void
  37.      * @returns void
  38.      * @see     http://www.phpdig.net/ref/rn45re877.html
  39.      */
  40.     function _detect()
  41.     {
  42.         // A hex number that may represent 'abyz'
  43.         $abyz = 0x6162797A;
  44.  
  45.         // Convert $abyz to a binary string containing 32 bits
  46.         // Do the conversion the way that the system architecture wants to
  47.         switch (pack ('L', $abyz))
  48.         {
  49.             // Compare the value to the same value converted in a Little-Endian fashion
  50.             case pack ('V', $abyz):
  51.                 $this->endian = "little";
  52.                 break;
  53.  
  54.             // Compare the value to the same value converted in a Big-Endian fashion
  55.             case pack ('N', $abyz):
  56.                 $this->endian = "big";
  57.                 break;
  58.  
  59.             default:
  60.                 $this->endian = "unknown";
  61.                 break;
  62.         }
  63.     }
  64.  
  65.     /**
  66.      * called by fopen() to the stream
  67.      * @param   (string)    $path           file path
  68.      * @param   (string)    $mode           stream open mode
  69.      * @param   (int)       $options        stream options (STREAM_USE_PATH |
  70.      *                                      STREAM_REPORT_ERRORS)
  71.      * @param   (string)    $opened_path    stream opened path
  72.      */
  73.     function stream_open($path, $mode, $options, &$opened_path)
  74.     {
  75.         $url = parse_url($path);
  76.         $this->xlsfilename= $url['host'] . $url['path'];
  77.         $this->position = 0;
  78.         $this->mode = $mode;
  79.  
  80.         $this->_detect();   // detect endian mode
  81.  
  82.         //@TODO: test for invalid mode and trigger error if required
  83.  
  84.         // open underlying resource
  85.         $this->fp = @fopen($this->xlsfilename, $this->mode);
  86.         if (is_resource($this->fp))
  87.         {
  88.             // empty the buffer
  89.             $this->buffer = "";
  90.  
  91.             if (preg_match("/^w|x/", $this->mode))
  92.             {
  93.                 // write an Excel stream header
  94.                 $str = pack(str_repeat($this->bin[$this->endian], 6), 0x809, 0x8, 0x0, 0x10, 0x0, 0x0);
  95.                 fwrite($this->fp, $str);
  96.                 $opened_path = $this->xlsfilename;
  97.                 $this->position = strlen($str);
  98.             }
  99.         }
  100.         return is_resource($this->fp);
  101.     }
  102.  
  103.     /**
  104.      * read the underlying stream resource (automatically called by fread/fgets)
  105.      * @todo    modify this to convert an excel stream to an array
  106.      * @param   (int)       $byte_count     number of bytes to read (in 8192 byte blocks)
  107.      */
  108.     function stream_read($byte_count)
  109.     {
  110.         if (is_resource($this->fp) && !feof($this->fp))
  111.         {
  112.             $data .= fread($this->fp, $byte_count);
  113.             $this->position = strlen($data);
  114.         }
  115.         return $data;
  116.     }
  117.  
  118.     /**
  119.      * called automatically by an fwrite() to the stream
  120.      * @param   (string)    $data           serialized array data string
  121.      *                                      representing a tabular worksheet
  122.      */
  123.     function stream_write($data)
  124.     {
  125.         // buffer the data
  126.         $this->buffer .= $data;
  127.         $bufsize = strlen($data);
  128.         return $bufsize;
  129.     }
  130.  
  131.     /**
  132.      * pseudo write function to manipulate the data
  133.      * stream before writing it
  134.      * modify this to suit your data array
  135.      * @access  private
  136.      * @param   (array)     $data           associative array representing
  137.      *                                      a tabular worksheet
  138.      */
  139.     function _xls_stream_write($data)
  140.     {
  141.         if (is_array($data) && !empty($data))
  142.         {
  143.             $row = 0;
  144.             foreach (array_values($data) as $_data)
  145.             {
  146.                 if (is_array($_data) && !empty($_data))
  147.                 {
  148.                     if ($row == 0)
  149.                     {
  150.                         // write the column headers
  151.                         foreach (array_keys($_data) as $col => $val)
  152.                         {
  153.                             // next line intentionally commented out
  154.                             // since we don't want a warning about the
  155.                             // extra bytes written
  156.                             // $size += $this->write($row, $col, $val);
  157.                             $this->_xlsWriteCell($row, $col, $val);
  158.                         }
  159.                         $row++;
  160.                     }
  161.  
  162.                     foreach (array_values($_data) as $col => $val)
  163.                     {
  164.                         $size += $this->_xlsWriteCell($row, $col, $val);
  165.                     }
  166.                     $row++;
  167.                 }
  168.             }
  169.         }
  170.         return $size;
  171.     }
  172.  
  173.     /**
  174.      * Excel worksheet cell insertion
  175.      * (single-worksheet supported only)
  176.      * @access  private
  177.      * @param   (int)       $row            worksheet row number (0...65536)
  178.      * @param   (int)       $col            worksheet column number (0..255)
  179.      * @param   (mixed)     $val            worksheet row number
  180.      */
  181.     function _xlsWriteCell($row, $col, $val)
  182.     {
  183.         if (is_float($val) || is_int($val))
  184.         {
  185.             // doubles, floats, integers
  186.             $str  = pack(str_repeat($this->bin[$this->endian], 5), 0x203, 14, $row, $col, 0x0);
  187.             $str .= pack("d", $val);
  188.         }
  189.         else
  190.         {
  191.             // everything else is treated as a string
  192.             $l    = strlen($val);
  193.             $str  = pack(str_repeat($this->bin[$this->endian], 6), 0x204, 8 + $l, $row, $col, 0x0, $l);
  194.             $str .= $val;
  195.         }
  196.         fwrite($this->fp, $str);
  197.         $this->position += strlen($str);
  198.         return strlen($str);
  199.     }
  200.  
  201.     /**
  202.      * called by an fclose() on the stream
  203.      */
  204.     function stream_close()
  205.     {
  206.         if (preg_match("/^w|x/", $this->mode))
  207.         {
  208.             // flush the buffer
  209.             $bufsize = $this->_xls_stream_write(unserialize($this->buffer));
  210.  
  211.             // ...and empty it
  212.             $this->buffer = null;
  213.  
  214.             // write the xls EOF
  215.             $str = pack(str_repeat($this->bin[$this->endian], 2), 0x0A, 0x00);
  216.             $this->position += strlen($str);
  217.             fwrite($this->fp, $str);
  218.         }
  219.  
  220.         // ...and close the internal stream
  221.         return fclose($this->fp);
  222.     }
  223.  
  224.     function stream_eof()
  225.     {
  226.         $eof = true;
  227.         if (is_resource($this->fp))
  228.         {
  229.             $eof = feof($this->fp);
  230.         }
  231.         return $eof;
  232.     }  
  233. }
  234.  
  235. stream_wrapper_register("xlsfile", "xlsStream")
  236.     or die("Failed to register protocol: xlsfile");
  237. ?>

Código PHP:
Ver original
  1. excel-ext.php
  2.  
  3. <?php
  4.  
  5. function createExcel($filename, $arrydata) {
  6. $excelfile = 'xlsfile://'.$filename;
  7. $fp = fopen($excelfile, "w+");
  8. if (!is_resource($fp)) {
  9. die('Error al crear $excelfile');
  10. }
  11. fwrite($fp, serialize($arrydata));
  12. fclose($fp);
  13.  
  14. header('Content-type: application/xls');
  15. header ("Content-Disposition: attachment; filename=\"" . $filename . "\"" );
  16. readfile($excelfile);
  17.  
  18. }
  19. ?>

Código PHP:
Ver original
  1. mysql.php
  2.  
  3. <?php
  4. require_once("excel.php");
  5. require_once("excel-ext.php");
  6.  
  7. $conEmp = mysql_connect("*****", "*****", "******");
  8. mysql_select_db("base_mexico", $conEmp);
  9. $queEmp = "SELECT Folio,Nombre,Radios,Ciudad,Respuesta,Observaciones_Investigacion,Respuesta_Reinvestigacion,
  10. Observaciones_Reinvestigacion,Fecha_Solicitud,Agencia,Tipo_Contrato,Fecha_Recepcion,Local_Foranea,Municipio_Delegacion,Causa,
  11. Causa_Reinvestigacion FROM layout ORDER BY Id DESC";
  12. $resEmp = mysql_query($queEmp, $conEmp) or die(mysql_error());
  13. $totEmp = mysql_num_rows($resEmp);
  14.  
  15. while($datatmp = mysql_fetch_assoc($resEmp)) {
  16.     $data[] = $datatmp;
  17. }  
  18. createExcel("Layout_Mexico.xls", $data);
  19. ?>
  #3 (permalink)  
Antiguo 18/12/2009, 12:38
Avatar de abimaelrc
Colaborador
 
Fecha de Ingreso: mayo-2009
Ubicación: En el planeta de Puerto Rico
Mensajes: 14.734
Antigüedad: 14 años, 10 meses
Puntos: 1517
Respuesta: Una ayudita con importar mysql a excel

El error parece estar en el metodo stream_open(). ¿Qué versión usas en tu local y que versión usas en tu hosting de PHP?
__________________
Verifica antes de preguntar.
Los verdaderos amigos se hieren con la verdad, para no perderlos con la mentira. - Eugenio Maria de Hostos
  #4 (permalink)  
Antiguo 18/12/2009, 12:52
 
Fecha de Ingreso: julio-2009
Mensajes: 63
Antigüedad: 14 años, 9 meses
Puntos: 0
Respuesta: Una ayudita con importar mysql a excel

Cita:
Iniciado por abimaelrc Ver Mensaje
El error parece estar en el metodo stream_open(). ¿Qué versión usas en tu local y que versión usas en tu hosting de PHP?
Gracias por la respuesta, mira en mi host utilizo la version 4.4.7 y en mi servidor local la version 5.1.6, en caso de que fuera problema de versiones crees que exista alguna forma de solventar esta situacion ???
  #5 (permalink)  
Antiguo 18/12/2009, 12:54
Avatar de abimaelrc
Colaborador
 
Fecha de Ingreso: mayo-2009
Ubicación: En el planeta de Puerto Rico
Mensajes: 14.734
Antigüedad: 14 años, 10 meses
Puntos: 1517
Respuesta: Una ayudita con importar mysql a excel

El problema es que entre PHP4 y PHP5 hay un gran cambio en las clases, por ejemplo PHP4 no reconoce public, private y protected. Vas a tener que ver si para tu hosting pueden hacer un cambio a la versión 5 o modificar la clase.
__________________
Verifica antes de preguntar.
Los verdaderos amigos se hieren con la verdad, para no perderlos con la mentira. - Eugenio Maria de Hostos
  #6 (permalink)  
Antiguo 18/12/2009, 13:07
 
Fecha de Ingreso: julio-2009
Mensajes: 63
Antigüedad: 14 años, 9 meses
Puntos: 0
Respuesta: Una ayudita con importar mysql a excel

Cita:
Iniciado por abimaelrc Ver Mensaje
El problema es que entre PHP4 y PHP5 hay un gran cambio en las clases, por ejemplo PHP4 no reconoce public, private y protected. Vas a tener que ver si para tu hosting pueden hacer un cambio a la versión 5 o modificar la clase.
A perfecto, eso yo no lo sabia por que de hecho se ha de notar que soy muy nuevo en esto de php, te agradezco mucho la respuesta y voy a probar llamando al personal del hosting a ver si me pueden resolver algo, de igual manera sigo en el post comentando si esta es la solucion o encontramos algun otro camino.

Sin animo de adular, quiero felicitarte por tus conocimientos en php, una semana me he dado de topes y tu en 2 minutos me dices la causa del problema.

Te deseo una excelente tarde.
  #7 (permalink)  
Antiguo 06/01/2010, 18:52
 
Fecha de Ingreso: julio-2009
Mensajes: 63
Antigüedad: 14 años, 9 meses
Puntos: 0
Respuesta: Una ayudita con importar mysql a excel

Cita:
Iniciado por abimaelrc Ver Mensaje
El problema es que entre PHP4 y PHP5 hay un gran cambio en las clases, por ejemplo PHP4 no reconoce public, private y protected. Vas a tener que ver si para tu hosting pueden hacer un cambio a la versión 5 o modificar la clase.
Hola abimaelrc fijate que hice lo que me sugeriste, cambie mi version del php a la 5.2.6 y el error sigue apareciendo, no logro exportar mi tabla mysql a excel.
Mencionas que se podria modificar la clase, pero en este caso si estoy frio por que no se a que te refieres, me podrias orientar un poco por favor ??? es que realmente me es de suma importancia poder realizar este procedimiento mediante mi pagina web.

Realmente no se casi nada de php, apenas estoy empezando pero he tenido buenos resultados y con ayuda del foro he ido logrando varias cosas, pero no se realmente a que clase es a la que te refieres que podria modificar, si pudieras echarme una mano quedaria en deuda contigo.

De antemano te agradezco tu atencion y te deseo un excelente año 2010.
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




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