Generar archivo de Excel

156 views
Skip to first unread message

NAIJULU

unread,
Aug 31, 2011, 11:06:17 AM8/31/11
to KumbiaPHP Framework
Buenos días,

Estoy siguiendo éste tutorial http://wiki.kumbiaphp.com/Generar_y_Leer_archivos_excel_(xls)_con_KumbiaPHP
para generar un archivo de Excel con datos que tengo en mi base de
datos, alli mencionan que debo usar un $this->set_response('xls') en
el controlador y crear una vista con el nombre sendFile.xls.phtml por
que le estamos indicando una salida xls en beta1 $this-
>set_response('xls') el problema radica en que al ejecutar el método
me arroja la siguiente excepción:

KumbiaException: Vista fileRuedaNegocios.phtml no encontrada (0)
En el archivo /home/market01/public_html/forms/core/kumbia/view.php en
la línea: 79

y no megenera el archivo de excel.

¿Alguien podría ayudarme a encontrar el error?

Datos:
Versión Framework Beta 1
Versión PHP 5.2.17

Henry Stivens

unread,
Aug 31, 2011, 11:47:37 AM8/31/11
to kum...@googlegroups.com
No recuerdo muy bien... pero intenta creando una carpeta donde están las vistas con el nombre xls y alli pon la vista  => fileRuedaNegocios.phtml

2011/8/31 NAIJULU <bel...@gmail.com>

--
Viva KumbiaPHP Framework!
 http://www.kumbiaphp.com/
 Ha recibido este mensaje porque está suscrito a Grupo "KumbiaPHP Framework" de Grupos de Google.
 Para obtener más opciones, visita este grupo en http://groups.google.com/group/kumbia?hl=es.



--
Henry Stivens Adarme Muñoz


Belmar Santanilla Gutiérrez

unread,
Aug 31, 2011, 12:01:33 PM8/31/11
to kum...@googlegroups.com
Hola Henry Stivens, gracias por responder.

Hice lo que me dijiste, cree una carpeta con el nombre xls dentro de views y allí puse el archivo fileRuedaNegocios.phtml y sigue saliendo la misma excepción, de igual forma también lo puse como dice en el tutorial fileRuedaNegocios.xls.phtml y sigue mostrando el mismo error. Muchas gracias.

2011/8/31 Henry Stivens <maxte...@gmail.com>



--

______________________________________
BELMAR SANTANILLA GUTIÉRREZ                            
Analísta de aplicaciones

Henry Stivens

unread,
Aug 31, 2011, 12:19:34 PM8/31/11
to kum...@googlegroups.com
Hola!

es decir que creaste...

app/views/xls/

¿?

debe ser:

app/views/controlador/xls/

Donde controlador es el nombre de tu controlador

2011/8/31 Belmar Santanilla Gutiérrez <bel...@gmail.com>

Belmar Santanilla Gutiérrez

unread,
Aug 31, 2011, 12:30:10 PM8/31/11
to kum...@googlegroups.com
Muchas gracias Henry, logré que descargara el .xls, pero los lios parecen no terminar... cuando abro el archivo generado viene en cada fila con errores, éstos son los errores:

Notice: Undefined variable: title in /home/market01/public_html/forms/app/views/templates/circulart.phtml on line 5 -> éste es por que yo uso variable title, si pongo el title me sale en la fila lo que ponga en la variable.

Strict Standards: Non-static method OLE::Asc2Ucs() should not be called statically, assuming $this from incompatible context in /home/market01/public_html/forms/core/vendors/excel/writer/workbook.php on line 586

Warning: tempnam() [function.tempnam]: open_basedir restriction in effect. File() is not within the allowed path(s): (/home/market01:/usr/lib/php:/usr/local/lib/php:/tmp) in /home/market01/public_html/forms/core/vendors/excel/OLE/PPS/file.php on line 87

Strict Standards: Non-static method PEAR::getStaticProperty() should not be called statically, assuming $this from incompatible context in /home/market01/public_html/forms/core/vendors/excel/main.php on line 906

Strict Standards: is_a(): Deprecated. Please use the instanceof operator in /home/market01/public_html/forms/core/vendors/excel/main.php on line 320

Strict Standards: Non-static method PEAR::getStaticProperty() should not be called statically, assuming $this from incompatible context in /home/market01/public_html/forms/core/vendors/excel/main.php on line 906

Strict Standards: is_a(): Deprecated. Please use the instanceof operator in /home/market01/public_html/forms/core/vendors/excel/main.php on line 320

Strict Standards: Non-static method PEAR::getStaticProperty() should not be called statically, assuming $this from incompatible context in /home/market01/public_html/forms/core/vendors/excel/main.php on line 906

Strict Standards: is_a(): Deprecated. Please use the instanceof operator in /home/market01/public_html/forms/core/vendors/excel/main.php on line 320

Strict Standards: Non-static method PEAR::getStaticProperty() should not be called statically, assuming $this from incompatible context in /home/market01/public_html/forms/core/vendors/excel/main.php on line 906

Muchas gracias a todos.


2011/8/31 Henry Stivens <maxte...@gmail.com>

Henry Stivens

unread,
Aug 31, 2011, 12:40:58 PM8/31/11
to kum...@googlegroups.com
La verdad ya se me sale de las manos...

No se que problema haya con la librería.

Belmar Santanilla Gutiérrez

unread,
Aug 31, 2011, 1:06:09 PM8/31/11
to kum...@googlegroups.com
Comprendo, muchas gracias. ¿Alguien más sabrá que sucede? ¿Existe otro método para generar archivos excel usando KumbiaPHP?

2011/8/31 Henry Stivens <maxte...@gmail.com>

Robert Babilonia

unread,
Aug 31, 2011, 1:13:22 PM8/31/11
to kum...@googlegroups.com
Hola Belmar,

en algún momento tuve el problema de estos mensajes al generar los xls, lo solucioné agregando al principio de cada vista (donde se genera el archivo xls) lo siguiente:

 ini_set('display_errors', 'Off');

Claro, seguro hay una manera mas elegante de arreglarlo, pero al menos a mi me funcionó en su momento.

El problema que tendrás con esto, es que no vas a poder ver los errores que obtengas mientras construyes tu archivo (me refiero a errores de programacion, como una variable no delcarada o algo así), pero para generar el archivo final, tal vez te sirva lo anteriormente mostrado.

En un foro encontré algo sobre el mensaje del Strict Standards: http://drupal.org/node/715768

Allí menciona en una de las respuestas:

"The error is shown because in the php.ini file of your php server, the error reporting is set to strict: E_STRICT. If you set the error message to E_ALL you will not have this problem."


Prueba con esto también a ver si avanzas un poco con la solución de tu problema...

Espero te sirva de ayuda.

Saludos.
Robert Babilonia Argüello.
Ingeniería de Sistemas, UNEFA.
Desarrollador de Aplicaciones, ASINCRO C.A.
IBM Certified.
Bobba...@hotmail.com
Bobba...@gmail.com

RBabi...@asincro.com

Belmar Santanilla Gutiérrez

unread,
Aug 31, 2011, 3:28:01 PM8/31/11
to kum...@googlegroups.com
Buenas tardes Robert Babilonia,

Gracias por responder, te comento que con lo que me dices efectivamente no salen errores, pero se genera un xls vacío. si uso la variable $this->title me pone en la primer fila, primer columna el valor de esa variable, al parecer envía como un html y con eso hace el documento. Probaré agregando  header ("Content-type: application/x-msexcel"); Si alguien sabe más sobre el tema, lo agradezco.

2011/8/31 Robert Babilonia <bobba...@gmail.com>

Belmar Santanilla Gutiérrez

unread,
Aug 31, 2011, 3:33:10 PM8/31/11
to kum...@googlegroups.com
Muchachos, les cuento que agregué la línea que les comenté y sigue generando el excel vacío... agradezco sus aportes

Robert Babilonia

unread,
Aug 31, 2011, 7:39:57 PM8/31/11
to kum...@googlegroups.com
Hola, me he puesto a hacer el tutorial que has indicado, usando la beta 1 de Kumbia y me ha salido, con la unica diferencia que he agregado lo siguiente:



En el controlador:


public function sendFile(){
        //View::response('xls');
                $this->template=NULL; // de lo contrario me envia el codigo del template dentro del xls
                $this->set_response("xls");
        $usuarios = new Usuarios();
        if(!$this->usuarios = $usuarios->find()){
            Flash::warning('No existen registros para exportar');
            $this->render(NULL);
        }
               
              
    }


Y en la vista he agregado al inicio sólo:


ini_set('display_errors', 'Off');


Con esto me ha funcionado el ejemplo, ya que al no colocar la línea anterior, el xls sale con los mensajes de 'strict' que tu mencionaste.

Si quieres agregar parte del código de lo que estas haciendo tal vez se te pueda ayudar mejor.

Belmar Santanilla Gutiérrez

unread,
Aug 31, 2011, 8:47:42 PM8/31/11
to kum...@googlegroups.com
Hola Robert, muchas gracias por responder. Te cuento que hice lo que me mencionaste y el error persiste, voy a mostrarles mi código tal vez esté cometiendo un error y no me he percatado:

Método: 

public function fileRuedaNegocios($key=null){
        $this->template = NULL;
        $this->set_response("xls");
        //Verifico que se incluya la llave
        if($key != null){
            //Verifico que la llave sea correcta
            if($key == "525294a5a393541dc62f7f69b3c48aee"){
                Load::lib('excel');                
                $registros = new ruedanegocios();
                if(!$this->registros = $registros->getRecord()){
                    Flash::warning('No existen registros.');
                    $this->render(NULL);
                }                
            }
            else{ 
            Flash::warning('La llave ingresada no es correcta. Contacte el administrador');
            $this->render(NULL);
            }
        }
        else{
            Flash::warning('Debes ingresar una llave. Contacte el administrador');
            $this->render(NULL);
        }
    }

Y La vista ubicada en /views/controlador/xls/fileRuedaNegocios.phtml

<?php
ini_set('display_errors', 'Off');
// Creo una instancia de la clase para escribir un documento excel
$libro = new Spreadsheet_Excel_Writer();
// Creo una hoja, puedo crear N número de hojas
$hoja1 = $libro->addWorksheet('Rueda Negocios');
// Charset
$hoja1->setInputEncoding('utf-8');
// Formato de letra
$negrita =& $libro->addFormat();
$negrita->setBold();

// Titulos (banda, documento, nombres, apellidos, mail, celular, telefono)
$hoja1->write(0, 0, "Banda", $negrita);
$hoja1->write(0, 1, "Documento", $negrita);
$hoja1->write(0, 2, "Nombres", $negrita);
$hoja1->write(0, 3, "Apellidos", $negrita);
$hoja1->write(0, 4, "Mail", $negrita);
$hoja1->write(0, 5, "Celular", $negrita);
$hoja1->write(0, 6, "Teléfono", $negrita); 

// Detalle
$row = 1;
foreach($registros as $item){
    $hoja1->write($row,0,$item->banda);
    $hoja1->write($row,1,$item->documento);
    $hoja1->write($row,2,$item->nombres);
    $hoja1->write($row,3,$item->apellidos);
    $hoja1->write($row,4,$item->mail);
    $hoja1->write($row,5,$item->celular);
    $hoja1->write($row,6,$item->telefono);
    $row ++;
}
$libro->send('rueda_negocios.xls');
$libro->close();
?>

Gracias por su ayuda, sus comentarios son muy valiosos.

2011/8/31 Robert Babilonia <bobba...@gmail.com>

Onizukar

unread,
Aug 31, 2011, 9:26:24 PM8/31/11
to kum...@googlegroups.com
Hola
revise el código y no veo por ningún lado la variable title que le aparece en un error

para hacer lo que requiere yo le recomiendo dos cosas

  1. en vez de poner  $this->set_response("xls"); en el controller yo pongo $this->set_response("view");
  2. no esta mal tener un if(isset($registros)) global en la vista
  3. Cargue la lib en la vista
estoy atento


Belmar Santanilla Gutiérrez

unread,
Aug 31, 2011, 9:34:15 PM8/31/11
to kum...@googlegroups.com
Hola Onizukar,

Realicé los cambios que mencionaste y el archivo sigue vacío. Si lo abro con gedit por ejemplo me muestra el HTML. Gracias por tu aporte.

2011/8/31 Onizukar <ooni...@gmail.com>

--
Viva KumbiaPHP Framework!
http://www.kumbiaphp.com/
Ha recibido este mensaje porque está suscrito a Grupo "KumbiaPHP Framework" de Grupos de Google.
Para obtener más opciones, visita este grupo en http://groups.google.com/group/kumbia?hl=es.

Henry Malas

unread,
Sep 1, 2011, 2:09:14 PM9/1/11
to kum...@googlegroups.com
El Html de....tu template??

Estas seguro que has incluido el:

$this->template=null;

No deberia de tener ningun código html.

Belmar Santanilla Gutiérrez

unread,
Sep 1, 2011, 2:27:46 PM9/1/11
to kum...@googlegroups.com
Si, mira el código del método

    public function fileRuedaNegocios($key=null){
        $this->template = NULL;
        $this->set_response("view");
        //Verifico que se incluya la llave
        if($key != null){
            //Verifico que la llave sea correcta
            if($key == "525294a5a393541dc62f7f69b3c48aee"){                            
                $registros = new ruedanegocios();
                if(!$this->registros = $registros->getRecord()){
                    Flash::warning('No existen registros.');
                    $this->render(NULL);
                }                
            }
            else{ 
            Flash::warning('La llave ingresada no es correcta. Contacte el administrador');
            $this->render(NULL);
            }
        }
        else{
            Flash::warning('Debes ingresar una llave. Contacte el administrador');
            $this->render(NULL);
        }
    }

Y aún así me sale el html en el archivo.

2011/9/1 Henry Malas <henry...@gmail.com>

Madelyn Del Rosario Cruz

unread,
Mar 18, 2012, 9:49:05 PM3/18/12
to kum...@googlegroups.com
Saludo,

Me el excel no se me generaba al igual que a Belmar.  Lo solucioné y si por si acaso alguien le pasa lo mismo, lo único es que en el Beta2
se debe cambiar  $this->template=NULL por View::template(NULL).

Madelyn :-)

El 1 de septiembre de 2011 14:27, Belmar Santanilla Gutiérrez <bel...@gmail.com> escribió:
Si, mira el código del método

    public function fileRuedaNegocios($key=null){
        $this->template = NULL;
        $this->set_response("view");
        //Verifico que se incluya la llave
        if($key != null){
            //Verifico que la llave sea correcta
            if($key == "525294a5a393541dc62f7f69b3c48aee"){                            
                $registros = new ruedanegocios();
                if(!$this->registros = $registros->getRecord()){
                    Flash::warning('No existen registros.');
                    $this->render(NULL);
                }                
            }
            else{ 
            Flash::warning('La llave ingresada no es correcta. Contacte el administrador');
            $this->render(NULL);
            }
        }
        else{
            Flash::warning('Debes ingresar una llave. Contacte el administrador');
            $this->render(NULL);
        }
    }

Y aún así me sale el html en el archivo.


--
Madelyn Del Rosario Cruz
Efficientia.com  | http://www.puertoplata.com.dohttp://www.educando.edu.do

"Mi vida carece de valor para mí mismo, con tal de que termine mi carrera y lleve a cabo el servicio que me ha encomendado el Señor Jesús, que es el de dar testimonio del evangelio de la gracia de Dios". Hechos 20:24 (NVI).

Blog: http://educanblog.educando.edu.do/index.php?blogId=18
Reply all
Reply to author
Forward
0 new messages