Exportar datos a Excel con KumbiaPHP

919 views
Skip to first unread message

Yader Centeno

unread,
Dec 1, 2013, 6:56:55 PM12/1/13
to kum...@googlegroups.com
Hola compañeros de KumbiaPHP:

A como he mencionado en otros correos (para los que han visto mis correos), estoy trabajando una aplicación PHP/MySQl con KumbiaPHP, especificamente con el Backend de Ivan Meléndez, que me está sirviendo mucho para aprender y como base para iniciar este nuevo proyecto que quiero hacer.

Quisiera poder exportar datos (de una tabla de mi BD MySQL o mucho mejor de un SQL construido con INNER JOINS que tengo en mi modelo) a Excel con KumbiaPHP (especificamente con el Backed de Ivan).  He intentado con este artículo de la Wiki: http://wiki.kumbiaphp.com/Generar_y_Leer_archivos_excel_%28xls%29_con_KumbiaPHP.  Pero primero NO encontraba la libería "excel", ahora la he buscado en la versión 1.0b de KumbiaPHP, la ponga en la carpeta core/libs y en core/vendors, según corresponde y todavía me da errores y hasta me dice que algunas funciones estan depreciadas o sea que ya no es compatible con la actual versión de KumbiaPHP.

¿Alguien me podría ayudar? ¿Facilitar algún ejemplo de algo similar (exportar datos a Excel) que hayan hecho con KumbiaPHP?  Ivan, ¿podrías echarme una manito, por favor?     

También les pido su ayuda para hacer el proceso a la inversa (subir datos de excel a una tabla de mi Base de Datos), por fa!!!

De antemano les agradezco cualquier ayuda que me puedan brindar

Saludos,

Yader Centeno

Iván D. Meléndez

unread,
Dec 1, 2013, 7:01:36 PM12/1/13
to kum...@googlegroups.com

Hola! Para excel he trabajado con Phpexcel de codeplex, te la recomiendo, es muy intuitiva.

EDUARDYAZ

unread,
Dec 2, 2013, 11:01:26 PM12/2/13
to kum...@googlegroups.com
Hola yo trabajo con la clase de PHPexcel es muy buena.

la clase debes colocar en la carpeta libs de tu app
directorio
libs/PHPexcel.php
libs/PHPexcel =>todo el contenido de la carpeta

la consulta en la base se hace igual como imprimes en un listar

te dejo un ejemplo de como va en la vista

<?php

/** Error reporting */
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

define('EOL', (PHP_SAPI == 'cli') ? PHP_EOL : '<br />');

date_default_timezone_set('America/Bogota');

if (PHP_SAPI == 'cli')
    die('This example should only be run from a Web Browser');

/** Include PHPExcel */
Load::lib('PHPExcel');

$dir = dirname(APP_PATH) . "/public/";
$ruta = $dir . "img/default";

// Create new PHPExcel object
$objPHPExcel = new PHPExcel();

$objPHPExcel->getProperties()->setCreator("ASDIN-SHOP.COM")
        ->setLastModifiedBy("PIL")
        ->setTitle("LISTA DE PRODUCTOS")
        ->setSubject("Documento Generado por PHPExcel")
        ->setDescription("LISTA DE PRODUCTOS PIL.")
        ->setKeywords("LISTA DE PRODUCTOS PIL")
        ->setCategory("LISTA DE PRODUCTOS PIL");

// Se crea una primera hoja, que representa la fecha de venta
// Combinar celdas titulo
echo date('H:i:s'), " Merge cells", EOL;
$objPHPExcel->getActiveSheet()->setShowGridlines(false);
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(2); //ANCHO DE CELDAS
//$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(13);
$objPHPExcel->getActiveSheet()->mergeCells('B1:D6'); //CONVINAR CELDAS
$objPHPExcel->getActiveSheet()->mergeCells('E3:G3'); //CONVINAR CELDAS

$objPHPExcel->getActiveSheet()->setCellValue('E3', 'LISTA DE PRODUCTOS CON STOCK'); //CELDA Y CONTENIDO

$objPHPExcel->getActiveSheet()->setCellValue('B7', 'CODIGO PIL'); //CELDA Y CONTENIDO
$objPHPExcel->getActiveSheet()->setCellValue('C7', 'MARCA');
$objPHPExcel->getActiveSheet()->setCellValue('D7', 'PRODUCTO');
$objPHPExcel->getActiveSheet()->setCellValue('E7', '# PARTE');
$objPHPExcel->getActiveSheet()->setCellValue('F7', 'DESCRIPCION');
$objPHPExcel->getActiveSheet()->setCellValue('G7', 'DIMENSION');
$objPHPExcel->getActiveSheet()->setCellValue('H7', 'UNIDAD');
$objPHPExcel->getActiveSheet()->setCellValue('I7', 'PROVEEDOR');
$objPHPExcel->getActiveSheet()->setCellValue('J7', 'NUM. OFERTA');
$objPHPExcel->getActiveSheet()->setCellValue('K7', 'RESPONSABLE');
$objPHPExcel->getActiveSheet()->setCellValue('L7', 'FECHA COTIZACION');
$objPHPExcel->getActiveSheet()->setCellValue('M7', 'CANTIDAD');
$objPHPExcel->getActiveSheet()->setCellValue('N7', 'TIEMPO ENTREGA');
$objPHPExcel->getActiveSheet()->setCellValue('O7', 'PARTIDA ARANCELARIA');
$objPHPExcel->getActiveSheet()->setCellValue('P7', 'PORCENTAJE IMPORTACION');
$objPHPExcel->getActiveSheet()->setCellValue('Q7', 'PRECIO1');
$objPHPExcel->getActiveSheet()->setCellValue('R7', 'FECHA1');
$objPHPExcel->getActiveSheet()->setCellValue('S7', 'PRECIO2');
$objPHPExcel->getActiveSheet()->setCellValue('T7', 'FECHA2');
$objPHPExcel->getActiveSheet()->setCellValue('U7', 'PRECIO3');
$objPHPExcel->getActiveSheet()->setCellValue('V7', 'FECHA3');

$a = 8;
foreach ($productos as $key => $value):
    $objPHPExcel->getActiveSheet()->setCellValue('B' . $a, $value->codigo);
    $objPHPExcel->getActiveSheet()->setCellValue('C' . $a, $value->marca);
    $objPHPExcel->getActiveSheet()->setCellValue('D' . $a, $value->producto);
    $objPHPExcel->getActiveSheet()->setCellValue('E' . $a, $value->num_parte);
    $objPHPExcel->getActiveSheet()->setCellValue('F' . $a, $value->descripcion);
    $objPHPExcel->getActiveSheet()->setCellValue('G' . $a, $value->dimencion);
    $objPHPExcel->getActiveSheet()->setCellValue('H' . $a, $value->simbolo);
    $objPHPExcel->getActiveSheet()->setCellValue('I' . $a, $value->proveedor);
    $objPHPExcel->getActiveSheet()->setCellValue('J' . $a, $value->num_compra);
    $objPHPExcel->getActiveSheet()->setCellValue('K' . $a, $value->login);
    $objPHPExcel->getActiveSheet()->setCellValue('L' . $a, $value->fecha_compra);
    $objPHPExcel->getActiveSheet()->setCellValue('M' . $a, $value->cantidad);
    $objPHPExcel->getActiveSheet()->setCellValue('N' . $a, $value->tiempo_entrega);
    $objPHPExcel->getActiveSheet()->setCellValue('O' . $a, $value->partida_arancelaria);
    $objPHPExcel->getActiveSheet()->setCellValue('P' . $a, $value->porcentaje_importacion);
    $objPHPExcel->getActiveSheet()->setCellValue('Q' . $a, $value->getListadoPrecios($value->id)->precio);
    $objPHPExcel->getActiveSheet()->setCellValue('R' . $a, $value->getListadoPrecios($value->id)->fecha_compra);    

    foreach ($value->getListadoPrecios($value->id,2) as $precio):
        $objPHPExcel->getActiveSheet()->setCellValue('S'.$a, $precio->precio);
        $objPHPExcel->getActiveSheet()->setCellValue('T'.$a, $precio->fecha_compra);    
    endforeach;

    foreach ($value->getListadoPrecios($value->id, 3) as $precio):
        $objPHPExcel->getActiveSheet()->setCellValue('U'.$a, $precio->precio);
        $objPHPExcel->getActiveSheet()->setCellValue('V'.$a, $precio->fecha_compra);    
    endforeach;


    $a++;
endforeach;

//$objPHPExcel->getActiveSheet()->mergeCells('A28:B28');  // Just to test...
//$objPHPExcel->getActiveSheet()->unmergeCells('A28:B28'); // Just to test...
// Establecer las alineaciones
//echo date('H:i:s'), " Set alignments", EOL;
//$objPHPExcel->getActiveSheet()->getStyle('B7,C7,D7')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);//ALINEAR A LA DERECHA
$objPHPExcel->getActiveSheet()->getStyle('B7:V7')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER); //ALINEAR AL CENTRO
$objPHPExcel->getActiveSheet()->getStyle('B7:V7')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER); //ALINEAR AL CENTRO
$objPHPExcel->getActiveSheet()->getStyle('B7:V7')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('B7:V7')->getFont()->getColor()->setARGB(PHPExcel_Style_Color::COLOR_WHITE);
$objPHPExcel->getActiveSheet()->getStyle('B7:V7')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
$objPHPExcel->getActiveSheet()->getStyle('B7:V7')->getFill()->getStartColor()->setARGB(PHPExcel_Style_Color::COLOR_DARKBLUE); //COLOR DE FONDO

$objPHPExcel->getActiveSheet()->getStyle('E3')->getFont()->setBold(true);

$objPHPExcel->getActiveSheet()->getRowDimension('7')->setRowHeight(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(12);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(40);
$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(10);
$objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('L')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('M')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('N')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('O')->setWidth(25);
$objPHPExcel->getActiveSheet()->getColumnDimension('P')->setWidth(25);
$objPHPExcel->getActiveSheet()->getColumnDimension('Q')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('R')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('S')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('T')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('U')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('V')->setWidth(20);


// Definir fuentes
//echo date('H:i:s'), " Set fonts", EOL;
//$objPHPExcel->getActiveSheet()->getStyle('B1')->getFont()->setName('Candara');
// Agregar un dibujo a la hoja de cálculo
//echo date('H:i:s'), " Add a drawing to the worksheet", EOL;
$objDrawing = new PHPExcel_Worksheet_Drawing();
$objDrawing->setName('Logo');
$objDrawing->setDescription('Logo');
$objDrawing->setPath("$ruta/logo.png");
$objDrawing->setHeight(115);
$objDrawing->setCoordinates('B1');
$objDrawing->setWorksheet($objPHPExcel->getActiveSheet());


// llenar celdas
//echo date('H:i:s'), " Set fills", EOL;
//$objPHPExcel->getActiveSheet()->getStyle('A1:G1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
// COLOR CELDAS RELLENO
//$objPHPExcel->getActiveSheet()->getStyle('A1:G1')->getFill()->getStartColor()->setARGB('FF808080');
// Cambiar el nombre de primera hoja de cálculo
echo date('H:i:s'), " Rename first MATERIALES-PRODUCTOS", EOL;
$objPHPExcel->getActiveSheet()->setTitle('MATERIALES-PRODUCTOS');

// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);

/** Error reporting */
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

date_default_timezone_set('Europe/London');

Load::lib('PHPExcel/IOFactory');

// Save Excel 2007 file
echo date('H:i:s'), " Write to Excel2007 format", EOL;
$callStartTime = microtime(true);


header("Last-Modified:" . gmdate . ( "D, d MYH: i: s" ) . "GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check = 0, pre-check = 0", false);
header("Pragma: no-cache");
header('Content-Type: application / vnd.openxmlformats officedocument.spreadsheetml.sheet-');
header('Content-Disposition: attachment; filename = "LISTADO DE PRODUCTOS.xlsx"');

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
ob_end_clean();
$objWriter->save('php://output');
//$objWriter->save(str_replace('.phtml', '.xlsx', __FILE__));
exit;

// Save Excel 95 file
header("Last-Modified:" . gmdate . ( "D, d MYH: i: s" ) . "GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check = 0, pre-check = 0", false);
header("Pragma: no-cache");
header('Content-Type: application / vnd.openxmlformats officedocument.spreadsheetml.sheet-');
header('Content-Disposition: attachment; filename = "LISTADO DE PRODUCTOS.xlsx"');

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
ob_end_clean();
//$objWriter->save(str_replace('.phtml', '.xls', __FILE__));
$objWriter->save('php://output');
exit;
?>

Manuel Aguirre

unread,
Dec 3, 2013, 6:59:03 AM12/3/13
to KumbiaPHP Framework
Buenas, como recomendación adicional siempre es mejor pasar a una variable el activeSheet para no estar haciendo:

$objPHPExcel->getActiveSheet()->.....

es mejor:

$sheet = $objPHPExcel->getActiveSheet();

y luego si usar directamente $sheet->...

Saludos!!!

Manuel Aguirre

unread,
Dec 3, 2013, 7:03:26 AM12/3/13
to KumbiaPHP Framework

Yader Centeno

unread,
Dec 8, 2013, 2:43:16 PM12/8/13
to kum...@googlegroups.com
Hola a todos:

Gracias por sus recomendaciones.   He intentado usar el PHPExcel de Codeplex.com, según el código de ejemplo de EDUARYAZ y de manuel_j555.  Descargue el PHPExcel y lo copie completo en la carpeta "app/libs".

Sin embargo, cuando doy click en un botón (en mi vista "listar.phtml" que tengo para ir a la función de exportar (en mi controlador), solo se queda la ruedita del AJAX como que estuviera ocupado, pero de ahí no pasa.  ¿Qué estaré haciendo mal?  Porque no recibo ningún mensaje de error.   Aunque sinceramente, no se si el código que puse en el controlador (abajo detallado), es el correcto.

Les dejo mi código por si me pueden ayudar a ver donde estoy mal.  ¿Me podrían ayudar, por favor?

He creado la siguiente vista, que he llamado ":
<?php
/** Error reporting */
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

Load::lib('PHPExcel');
Load::lib('PHPExcel/IOFactory');

//invoco la clase para generar el libro excel
$libro = new PHPExcel();
 
//creo una hoja, es decir, puedo crear N hojas
$hoja1 = $libro->getActiveSheet();
$hoja1->setTitle("presupuesto");
$hoja1->setShowGridlines(false);

//Tamaño de las columnas
$hoja1->getColumnDimension('A')->setWidth("10");
$hoja1->getColumnDimension('B')->setWidth("30");
$hoja1->getColumnDimension('C')->setWidth("100");
$hoja1->getColumnDimension('D')->setWidth("50");
$hoja1->getColumnDimension('E')->setWidth("50");
$hoja1->getColumnDimension('F')->setWidth("30");
$hoja1->getColumnDimension('G')->setWidth("30");
$hoja1->getColumnDimension('H')->setWidth("30");
$hoja1->getColumnDimension('I')->setWidth("30");
$hoja1->getColumnDimension('J')->setWidth("30");
$hoja1->getColumnDimension('K')->setWidth("30");
$hoja1->getColumnDimension('L')->setWidth("30");
$hoja1->getColumnDimension('M')->setWidth("30");
$hoja1->getColumnDimension('N')->setWidth("30");
$hoja1->getColumnDimension('O')->setWidth("30");
$hoja1->getColumnDimension('P')->setWidth("30");
$hoja1->getColumnDimension('Q')->setWidth("30");
$hoja1->getColumnDimension('R')->setWidth("30");

//a partir de que fila se mostrarán las descripciones, la primera son las cabeceras
$headerRow = 4;

//seteamos los valores de titulo y cabeceras
$hoja1->setCellValue("A1", "Presupuesto por Grupo de usuarios");
$hoja1->setCellValue("A{$headerRow}", "ID");
$hoja1->setCellValue("B{$headerRow}", "Periodo");
$hoja1->setCellValue("C{$headerRow}", "Cuenta");
$hoja1->setCellValue("D{$headerRow}", "Delegacion");
$hoja1->setCellValue("E{$headerRow}", "Grupo de usuarios");
$hoja1->setCellValue("F{$headerRow}", "Mes 1");
$hoja1->setCellValue("G{$headerRow}", "Mes 2");
$hoja1->setCellValue("H{$headerRow}", "Mes 3");
$hoja1->setCellValue("I{$headerRow}", "Mes 4");
$hoja1->setCellValue("J{$headerRow}", "Mes 5");
$hoja1->setCellValue("K{$headerRow}", "Mes 6");
$hoja1->setCellValue("L{$headerRow}", "Mes 7");
$hoja1->setCellValue("M{$headerRow}", "Mes 8");
$hoja1->setCellValue("N{$headerRow}", "Mes 9");
$hoja1->setCellValue("O{$headerRow}", "Mes 10");
$hoja1->setCellValue("P{$headerRow}", "Mes 11");
$hoja1->setCellValue("Q{$headerRow}", "Mes 12");
$hoja1->setCellValue("R{$headerRow}", "Notas");

//unimos las columnas A1 y E1 donde vá el título
$hoja1->mergeCells("A1:R1");
//acá sacamos la fila a partir de donde van las descripciones, luego de las cabeceras
$initialRow = $headerRow + 1;
$fila = $initialRow;

//recorremos las descripciones de cada presupuesto de grupo y seteamos los valores en la celdas
foreach($apresupareapag->items as $apresuparea):
    $hoja1->setCellValue("A{$fila}", $apresuparea->id);
    $hoja1->setCellValue("B{$fila}", $apresuparea->nombre_periodo);
    $hoja1->setCellValue("C{$fila}", $apresuparea->codigo_cta);
    $hoja1->setCellValue("D{$fila}", $apresuparea->codigo_area);
    $hoja1->setCellValue("E{$fila}", $apresuparea->nombre_grupo);
    $hoja1->setCellValue("F{$fila}", $apresuparea->mes1);
    $hoja1->setCellValue("G{$fila}", $apresuparea->mes2);
    $hoja1->setCellValue("H{$fila}", $apresuparea->mes3);
    $hoja1->setCellValue("I{$fila}", $apresuparea->mes4);
    $hoja1->setCellValue("J{$fila}", $apresuparea->mes5);
    $hoja1->setCellValue("K{$fila}", $apresuparea->mes6);
    $hoja1->setCellValue("L{$fila}", $apresuparea->mes7);
    $hoja1->setCellValue("M{$fila}", $apresuparea->mes8);
    $hoja1->setCellValue("N{$fila}", $apresuparea->mes9);
    $hoja1->setCellValue("O{$fila}", $apresuparea->mes10);
    $hoja1->setCellValue("P{$fila}", $apresuparea->mes11);
    $hoja1->setCellValue("Q{$fila}", $apresuparea->mes12);
    $hoja1->setCellValue("R{$fila}", $apresuparea->observaciones);

    ++$fila;
endforeach;

//anterior tendrá el valor de la ultima fila con descripción
$ultima = $fila - 1;

//Definimos los totales
$hoja1->setCellValue("E{$fila}", "TOTAL");
$hoja1->setCellValue("F{$fila}", "=SUM(F{$initialRow}:F{$ultima})");
$hoja1->setCellValue("G{$fila}", "=SUM(G{$initialRow}:G{$ultima})");
$hoja1->setCellValue("H{$fila}", "=SUM(H{$initialRow}:H{$ultima})");
$hoja1->setCellValue("I{$fila}", "=SUM(I{$initialRow}:I{$ultima})");
$hoja1->setCellValue("J{$fila}", "=SUM{J{$initialRow}:J{$ultima})");
$hoja1->setCellValue("K{$fila}", "=SUM(K{$initialRow}:K{$ultima})");
$hoja1->setCellValue("L{$fila}", "=SUM(L{$initialRow}:L{$ultima})");
$hoja1->setCellValue("M{$fila}", "=SUM(M{$initialRow}:M{$ultima})");
$hoja1->setCellValue("N{$fila}", "=SUM(N{$initialRow}:N{$ultima})");
$hoja1->setCellValue("O{$fila}", "=SUM(O{$initialRow}:O{$ultima})");
$hoja1->setCellValue("P{$fila}", "=SUM(P{$initialRow}:P{$ultima})");
$hoja1->setCellValue("Q{$fila}", "=SUM(Q{$initialRow}:Q{$ultima})");

$libro->setActiveSheetIndex(0);

// Guardar en Excel 2007 file

header("Last-Modified:" . gmdate . ( "D, d MYH: i: s" ) . "GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check = 0, pre-check = 0", false);
header("Pragma: no-cache");
header('Content-Type: application / vnd.openxmlformats officedocument.spreadsheetml.sheet-');
header('Content-Disposition: attachment; filename = "PRESUPUESTO.xlsx"');

$objWriter = PHPExcel_IOFactory::createWriter($libro, 'Excel2007');

ob_end_clean();
$objWriter->save('php://output');
exit;
?>

También he creado la siguiente función en el controlador:
<?php
public function exportar($order='order.id.asc', $page='pag.1', $grupo='0'){
        View::template(NULL); //Agregado para que no envié todo el html(Beta2). En Beta1 $this->template=NULL
        View::response('xls');

        $apresuparea = new Apresuparea();
        $this->apresupareapag = $apresuparea->getListadoApresuparea($order, $page, $grupo);
        $this->page = $page;
        $this->grupo = $grupo;
        $this->order = $order;
    }
?>

Y desde la vista principal "listar.phtml", he puesto un botón para hacer click y que me genere el archivo de excel:
<?php
echo DwHtml::button('presupuesto/apresuparea/exportar/order.id.asc/1/'.$grupo.'/', 'Exportar a Excel', array('class'=>'btn-info', 'id'=>'botonexportar'), 'print', APP_AJAX);
?>

Yader Centeno

unread,
Dec 8, 2013, 6:54:45 PM12/8/13
to kum...@googlegroups.com
Hola compañeros:

He logado solucionar el asunto de EXPORTAR los datos a Excel.  joanhey (del Chat de KumbiaPHP) me dió varias ideas, lo hice como que fuera otra vista, pero más sencilla con menos HTML solo como tabla y ciertos formatos que quería y la ubiqué en la carpeta app/views/_shared/templates. 

Luego solo fue modificar un poco los headers y desactivar el Ajax que trae por defecto los botones del backend de Ivan.

Sin embargo, todavía me queda la duda de como IMPORTAR datos desde Excel hacia KumbiaPHP.  ¿Alguna idea?

Gracias a todos por su ayuda, me han apoyado con muchas ideas, de verdad lo aprecio mucho.

Saludos,

Yader

Govani

unread,
Dec 9, 2013, 5:55:11 PM12/9/13
to kum...@googlegroups.com
He usado PHPExcel sin problemas en muchas ocasiones, te muestro parte del codigo para que veas lo que hago. en realidad despues de guardar el archivo, redireciono al archivo como tal lo que obligo a la descarga, lo hago sin ajax, claro que para archivos grandes si sera necesario

Load::lib("PHPExcel/PHPExcel");
class ExcelController extends AppController {
    public function bitacora($idBitacora) {
        View::select(null, null);

            ...

        $objPHPExcel->getActiveSheet()->getSheetView()->setView(PHPExcel_Worksheet_SheetView::SHEETVIEW_PAGE_LAYOUT);
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $nombre_archivo = uniqid() . ".xls";
        $objWriter->save(PATH_FILES . $nombre_archivo);
        $ip = $_SERVER['SERVER_ADDR'];
        $url = URL_DOMAIN . "/files/$nombre_archivo";
        header("location: " . $url);

EDUARDYAZ

unread,
Dec 29, 2013, 1:33:37 PM12/29/13
to kum...@googlegroups.com
hola Yaden un favor puede ayudarme como hiciste para exportar a excel con un ejemplo de antemano te lo agradesco

saludos

Gerardo Belot

unread,
Dec 29, 2013, 3:20:59 PM12/29/13
to kum...@googlegroups.com
Hay varias formas de hacerlo, pero la forma mas fácil será instalando http://datatables.net/ he instalando correctamente sus plug-in, así la exportacion la haces desde el cliente y evitar cargar el servidor-

La otra opción es instalando http://phpexcel.codeplex.com/, lo descargas a la carpeta libs y luego lo llamas al controlador mediante un Load::libs() , luego simplemente te creas el metodo que lo maneja con un view::render(xml) y obviamente la vista segun este tutorial

suerte


--
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.
---
Has recibido este mensaje porque estás suscrito al grupo "KumbiaPHP Framework" de Grupos de Google.
Para anular la suscripción a este grupo y dejar de recibir sus correos electrónicos, envía un correo electrónico a kumbia+un...@googlegroups.com.
Para obtener más opciones, visita https://groups.google.com/groups/opt_out.



--
Gerardo A. Belot

Yader Centeno

unread,
Dec 30, 2013, 2:29:11 PM12/30/13
to kum...@googlegroups.com
Hola Eduardyaz:

Te voy a adjuntar el código del modelo, del controlador y de la vista (que son 2: listar.phtml y acuentas.phtml)

Yo lo que hize para exportar datos a Excel fue lo siguiente:
1.  En mi modelo (archivo: acuentas.php), cree una función llamada getExportarAcuentas(), que busca y retorna los datos sin paginar
2.  En mi controlador (archivo: acuentas_controller.php), cree la función exportar(), que busca los datos y define la plantilla a utilizar (ubicada en el directorio app/views/_shared/templates/exportar).
3. En mi vista (archivo: listar.phtml) incluyo un botón con este código (linea 27 del archivo phtml):
echo DwHtml::button('config/acuentas/exportar/', 'Exportar a Excel', array('class'=>'btn-info no-ajax no-spinner'), 'download'); 
4. Creo un archivo llamado acuentas.phmtl dentro de la carpeta: app/views/_shared/templates/exportar/ con el codigo php y HTML que queres mostrar como datos (tabla de datos, titulos, etc.).  Este archivo hace la exportación a excel mediante los codigo php de las primeras 6 líneas de este archivo (acuentas.phtml).

Te podes guiar con el codigo que te adjunto, ya viendolo bien, no es tan dificil. A mi me ayudaron mucho en el IRC de KumbiaPHP.

Espero te pueda servir.

Saludos,

Yader Centeno
León, Nicaragua
acuentas.php
acuentas_controller.php
listar.phtml
acuentas.phtml

EDUARDYAZ

unread,
Jan 3, 2014, 6:43:18 PM1/3/14
to kum...@googlegroups.com
Hola Yader muchas gracias lo voy a revisar necesito otra opción a la de la librería de codeplex por que necesito generar un reporte que tiene una función re cursiva y genera un árbol pero no logre hacer con phpexcel la impresión del reporte.


Saludos
Message has been deleted

joanhey

unread,
Jan 15, 2014, 9:43:36 AM1/15/14
to kum...@googlegroups.com
La lib para generar que usaste si es compatible con todas las versiones de Kumbiaphp.
Lo que esa lib, que es de terceros (externa no de Kumbiaphp), no es compatible con las nuevas versiones de PHP

Reply all
Reply to author
Forward
0 new messages