SlideShare una empresa de Scribd logo
1 de 20
PHPExcel, libreria PHP para leer y escribir archivos de
Excel
07-07-2008 Tutoriales, Programación, Desarrollo Web 49734 hits (100 %) 44 comentarios




Creo que el título lo dice todo. Esta librería permite leer y manipular el contenido de una
hoja de cálculo hecha con Microsoft Excel. Vamos directo al grano y veamos un ejemplo.
Usaremos Microsoft Office Excel 2007 para la hoja de cálculo, ósea el archivo tendrá la
extensión xlsx. También usaremos la versión 5.2.x de PHP.

1. Descargue la libreriaPHPExcel

Descargamos la ultima versión. Después de descomprimirla ubicamos la carpeta Clases y
la movemos a una carpeta donde pondremos nuestro ejemplo para este caso se llamará
phpexcel_ejemplo. De tal manera que quede así: ruta_servidorphpexcel_ejemploClases.

2. Creamos un documentos de Excel

La hoja de cálculo tendrá el siguiente formato: (descargar archivo de ejemplo). La
ubicamos en la carpeta phpexcel_ejemplo.

3. Creamos la interfaz web

Mediante HTML creamos una formulario para el ingreso de los valores, y también
escribimos código para usar la librería PHPExcel. Este archio lo guardamos con el nombre
de index.phpen la carpeta phpexcel_ejemplo.

&nbsp;<?php
/** Incluir la ruta **/
set_include_path(get_include_path() . PATH_SEPARATOR .'./Classes/');

/** Clasesnecesarias */
require_once('PHPExcel.php');
require_once('PHPExcel/Reader/Excel2007.php');

// Variables de la página
$_VIEWDATA = array(
        'v_precioTotal' => 0,
        'v_descuento' => 0,
        'v_precioFinal' => 0
);

// Petición de cálculo?
if (isset($_REQUEST['boton_calcular'])) {
// Cargando la hoja de cálculo
        $objReader = new PHPExcel_Reader_Excel2007();
        $objPHPExcel = $objReader->load("calculo.xlsx");

        // Asignarhoja de calculoactiva
        $objPHPExcel->setActiveSheetIndex(0);

        // Asignar data
        $objPHPExcel->getActiveSheet()->setCellValue('automatico',
$_REQUEST['transmision_Automatica']);
        $objPHPExcel->getActiveSheet()->setCellValue('cuero',
$_REQUEST['asientos_Cuero']);
        $objPHPExcel->getActiveSheet()->setCellValue('suspension',
$_REQUEST['suspension']);

        // Calculos
        $_VIEWDATA['v_precioTotal'] = $objPHPExcel->getActiveSheet()-
>getCell('total')->getCalculatedValue();
        $_VIEWDATA['v_descuento'] = $objPHPExcel->getActiveSheet()-
>getCell('descuento')->getCalculatedValue();
        $_VIEWDATA['v_precioFinal'] = $objPHPExcel->getActiveSheet()-
>getCell('final')->getCalculatedValue();
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"
/>
<title>Ejemplo</title>
</head>

<body>
    <form id="formulario" method="post" name="formulario"
action="index.php">
        <table>
            <tr>
                 <th>Transmisi&oacute;nautom&aacute;tica :</th>
                 <td>
                      <select id="transmision_Automatica"
name="transmision_Automatica">
                          <?php
if(isset($_REQUEST['transmision_Automatica'])) { ?>
                          <option value="<?php echo
$_REQUEST['transmision_Automatica']; ?>" selected="selected"><?php echo
$_REQUEST['transmision_Automatica']; ?></option>
                          <?php } ?>
                          <optionvalue="No">No</option>
                          <optionvalue="Si">Si</option>
                      </select>
                 </td>
            </tr>
            <tr>
                 <th>Asientos de cuero:</th>
                 <td>
                      <select id="asientos_Cuero" name="asientos_Cuero">
<?phpif(isset($_REQUEST['asientos_Cuero'])) { ?>
                          <option value="<?php echo
$_REQUEST['asientos_Cuero']; ?>" selected="selected"><?php echo
$_REQUEST['asientos_Cuero']; ?></option>
                          <?php } ?>
                          <option value="No">No</option>
                          <option value="Si">Si</option>
                      </select>
                 </td>
            </tr>
            <tr>
                 <th>Suspensi&oacute;n:</th>
                 <td>
                      <select id="suspension" name="suspension">
                          <?php if(isset($_REQUEST['suspension'])) { ?>
                          <option value="<?php echo
$_REQUEST['suspension']; ?>" selected="selected"><?php echo
$_REQUEST['suspension']; ?></option>
                          <?php } ?>
                          <option value="No">No</option>
                          <option value="Si">Si</option>
                      </select>
                 </td>
            </tr>
            <tr>
                 <th>&nbsp;</th>
                 <td>
                      <input id="boton_calcular" name="boton_calcular"
type="submit" value="Calcular" />
                 </td>
            </tr>
        </table>
    </form>
    <?php if (isset($_REQUEST['boton_calcular'])) { ?>

    <h2>Detalles del Precio</h2>
    <p>Basado en tus preferencias, el precio de tu carro será S/. <?php
echo number_format($_VIEWDATA['v_precioFinal'], 2); ?> Nuevos Soles.</p>
    <table>
        <tr>
             <th>Precio Total:</th>
             <td><?php echo number_format($_VIEWDATA['v_precioTotal'], 2);
?>Nuevos Soles</td>
        </tr>
        <tr>
             <th>Descuento:</th>
             <td><?php echo number_format($_VIEWDATA['v_descuento'] * 100,
2); ?>%</td>
        </tr>
        <tr>
                 <td colspan="2"><hrnoshade="noshade"></hr>
        </tr>
        <tr>
             <th>Total Final:</th>
             <td><?php echo number_format($_VIEWDATA['v_precioFinal'], 2);
?>Nuevos Soles</td>
        </tr>
</table>
    <p><a href="index.php">Calcular nuevo precio</a></p>

    <?php } ?>
</body>
</html>

4. A probar ...!

Vamos al navegador web y escribirmoshttp://localhost/phpexcel_ejemplo/index.php y
tendremos una interfaz con los datos que obtenemos de la hoja de cálculo.

Seguramente se nos ocurrirá muchas cosas en la cual emplear está interesante librería. ¿Y
que tal si la combinamos con AJAX?. La librería PHPExcel contiene documentación
detallada para usarla correctamente, además de muchos otros ejemplos.
PHPExcel is a collection of classes that allows you to generate excel documents in PHP. It
is incredibly powerful and you can perform almost all (if not all) task that you would
normally use in excel.

It is really easy to install, either download the files or they now have a pear channel. For
more details visit the PHPExcel site.

This post is mainly for myself so that I can have a quick reference guide for common
functions. For full documentation see PHPExcel Documentation.

PHPExcel supports fluent interfaces so function calls can be chained together. The
following:

<?php
$sheet->setCellValue("A1", "Text");
$sheet->setCellValue("A2", "Text");
$sheet->setCellValue("A3", "Text");
$sheet->setCellValue("A4", "Text");
$sheet->setCellValue("A5", "Text");
view rawNormal.phpThis Gist brought to you by GitHub.

Can be written like:
<?php
$sheet->setCellValue("A1", "Text")
      ->setCellValue("A2", "Text")
      ->setCellValue("A3", "Text")
      ->setCellValue("A4", "Text")
      ->setCellValue("A5", "Text");
view rawFluentExample.phpThis Gist brought to you by GitHub.

Basics

       Create a new object: $phpExcel = new PHPExcel();
       Getting the active worksheet: $sheet = $phpExcel->getActiveSheet();
       Add text to a cell: $sheet->setCellValue("A1", "Hello World");
       Add a new worksheet: $sheet2 = $phpExcel->createSheet();
       Add a formula to a cell: $sheet2->setCellValue("A5", "=SUM(A1:A4)");
       Rename a worksheet: $sheet2->setTitle("Simple");
       Merge cells: $sheet2()->mergeCells("A1:E3");
       Unmerge cells: $sheet2()->unmergeCells("A1:E3");

Addingpropertiestoyour file

       Set Author: $phpExcel ->getProperties()->setCreator("Tom Smith");
       Set Last Modified By: $phpExcel->getProperties()-
       >setLastModifiedBy("Tom Smith");
       Set Title: $phpExcel->getProperties()->setTitle("Title");
       Set Subject: $phpExcel->getProperties()->setSubject("Subject");
Set Description: $phpExcel->getProperties()->setDescription("A
       description of the file.");

Formatting A Cell

       Setting Width: $sheet2->getColumnDimension("A")->setWidth(40);
       Setting Auto Width: $sheet2->getColumnDimension("A")-
       >setAutoSize(true);
       Setting Text Alignment Right: $sheet2->getStyle("A1")->getAlignment()-
       >setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
       Making text of a range of cells bold: $sheet2->getStyle("A1:F1")-
       >applyFromArray(array("font" => array( "bold" => true)));
       Adding an auto filter to a range of cells: $sheet2->setAutoFilter("A1:C9");

Output to the browser as a download.
<?php
$phpExcel = new PHPExcel();
$phpExcel->getActiveSheet()->setTitle("My Sheet");

$phpExcel->setActiveSheetIndex(0);
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename="filename.xls"");
header("Cache-Control: max-age=0");

$objWriter = PHPExcel_IOFactory::createWriter($phpExcel, "Excel5");
$objWriter->save("php://output");
exit;



****************************** EJEMPLO ****


PHPExcel Code Example
Posted on 8th April 2011 byTom Smith |

<?php
require_once("PHPExcel/PHPExcel.php");
$phpExcel=newPHPExcel();

$styleArray=array(
        'font'=>array(
                'bold'=>true,
        )
);

//Get the active sheet and assign to a variable
$foo=$phpExcel->getActiveSheet();

//add column headers, set the title and make the text bold
$foo->setCellValue("A1","Foo1")
->setCellValue("B1","Foo2")
       ->setCellValue("C1","Foo3")
       ->setCellValue("D1","Foo3")
       ->setTitle("Foo")
       ->getStyle("A1:D1")->applyFromArray($styleArray);

//Create a new sheet
$bar=$phpExcel->createSheet();
$bar->setCellValue("A1","Bar1")
        ->setCellValue("B1","Bar2")
        ->setCellValue("C1","Bar3")
        ->setCellValue("D1","Bar3")
        ->setTitle("Bar")
        ->getStyle("A1:D1")->applyFromArray($styleArray);

//When in loops you always need to use a counter to ensure data goes into
the next row.
for($rowCounter=2;$rowCounter<20;$rowCounter++){

        $foo->setCellValue("A$rowCounter","Row".($rowCounter-2))
                ->setCellValue("B$rowCounter",$rowCounter*2)
                ->setCellValue("C$rowCounter",$rowCounter/2)
                -
>setCellValue("D$rowCounter","=B$rowCounter+C$rowCounter");

        $bar->setCellValue("A$rowCounter","Row".($rowCounter-2))
                ->setCellValue("B$rowCounter",($rowCounter%2)?"Type
1":"Type2")
                ->setCellValue("C$rowCounter",str_repeat("foo
",rand(5,10)))
                ->setCellValue("D$rowCounter",str_repeat("%
",rand(20,50)));
}

//Merge the first two columns of the next row and sum columns C & D.
$foo->mergeCells("A$rowCounter:B$rowCounter");
$foo->setCellValue("A$rowCounter","Total")
        ->setCellValue("C$rowCounter","=SUM(C2:C".($rowCounter-1).")")
        ->setCellValue("D$rowCounter","=SUM(D2:D".($rowCounter-1).")");

//Set the text alignment to right for the total cell.
$foo->getStyle("A$rowCounter")->getAlignment()-
>setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);

//Set the column widths
$foo->getColumnDimension("A")->setWidth(40);
$foo->getColumnDimension("B")->setWidth(20);
$foo->getColumnDimension("C")->setWidth(20);
$foo->getColumnDimension("D")->setWidth(20);

$bar->getColumnDimension("A")->setAutoSize(true);
$bar->getColumnDimension("B")->setAutoSize(true);
$bar->getColumnDimension("C")->setAutoSize(true);
$bar->getColumnDimension("D")->setWidth(40);

//Wrap long fields
$bar->getStyle("D1:D20")->getAlignment()->setWrapText(true);
//Set the active sheet to the first sheet before outputting. This is only
needed if you want to ensure the file is opened on the first sheet.
$phpExcel->setActiveSheetIndex(0);

//Output the generated excel file so that the user can save or open the
file.
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename="example-excel-
file.xls"");
header("Cache-Control: max-age=0");

$objWriter=PHPExcel_IOFactory::createWriter($phpExcel,"Excel5");
$objWriter->save("php://output");
exit;




***********************¨¨¨¨¨¨¨¨¨¨¨¨¨¨**************

1.- DESCARGAR PHPExcel

Lo primero que debemos hacer es descargarnos la última versión de esta librería en la
página de descargas de PHPExcel y descomprimir el contenido en alguna carpeta de
nuestro proyecto PHP.

2.- MODO DE USO

Todas las librerías necesarias se encuentran en la carpeta Classes y debemos llamarlas con
require_once(). Y podemos crear un archivo .php, por ejemplo un archivo excel.php:
?
1require_once("Classes/PHPExcel.php");
2require_once("Classes/PHPExcel/Writer/Excel2007.php");
Luego creamos un OBJETO de la clase PHPExcel():
?
1$objPHPExcel= newPHPExcel();
Por último trabajamos con varios metodos de PHPExcel para generar un Excel:
?
1 //algunos datos sobre autoría
2 $objPHPExcel->getProperties()->setCreator("autor");
   $objPHPExcel->getProperties()->setLastModifiedBy("autor");
3 $objPHPExcel->getProperties()->setTitle("titulo del Excel");
4 $objPHPExcel->getProperties()->setSubject("Asunto");
5 $objPHPExcel->getProperties()->setDescription("Descripcion");
6
7 //Trabajamos con la hoja activa principal
   $objPHPExcel->setActiveSheetIndex(0);
8
9 //iteramos para los resultados
10foreach($filasas$row){
11      $objPHPExcel->getActiveSheet()->SetCellValue("B".$row["id_cli"],
12$row["rut_cli"]);
13     $objPHPExcel->getActiveSheet()->SetCellValue("C".$row["id_cli"],
   $row["nombre_cli"]);
14     $objPHPExcel->getActiveSheet()->setCellValue("D".$row["id_cli"],
15$row["correo_cli"]);
16     $objPHPExcel->getActiveSheet()->setCellValue("E".$row["id_cli"],
17 $row["telefono_cli"]);
       $objPHPExcel->getActiveSheet()->setCellValue("F".$row["id_cli"],
18$row["pais_cli"]);
19}
20
21//Titulo del libro y seguridad
22$objPHPExcel->getActiveSheet()->setTitle('Reporte');
23$objPHPExcel->getSecurity()->setLockWindows(true);
   $objPHPExcel->getSecurity()->setLockStructure(true);
24
25
26// Se modifican los encabezados del HTTP para indicar que se envia un
27archivo de Excel.
28header('Content-Type: application/vnd.openxmlformats-
29officedocument.spreadsheetml.sheet');
30header('Content-Disposition:
   attachment;filename="reporteClientes.xlsx"');
31header('Cache-Control: max-age=0');
32
33//Creamos el Archivo .xlsx
     $objWriter= PHPExcel_IOFactory::createWriter($objPHPExcel,
     'Excel2007');
     $objWriter->save('php://output');
Con esto podemos crear un enlace al archivo excel.php para generar un reporte en excel:
?
1<ahref="excel.php">Exportar a Excel</a>
Como ves, no es muy complicado crear archivos .xlsx. La documentación de esta gran
librería es muy amplia y se puede jugar con el diseño del archivo, las formulas, etc..




************************+ php-xcel-reader ************

<?
          include("class.excel.writer.php");
          $xls = new ExcelWriter();

          $xls_int = array('type'=>'int','border'=>'000000');
          $xls_date = array('type'=>'date','border'=>'000000');
          $xls_normal = array('border'=>'000000');

        $textos =
array('aaaabbbbccccddddd','bbbbaaaaadddd','ccccdsdsd','ddddasdfasdf','eee
easdfasdfw','erwssd ds werwwe v
ytjrhethwerwwejdrfgerwerwwekfghtrwerwwe','gggg','hhhh','iiii','kkkkkk');
$colores =
array('F17C0E','0012FF','06FF00','FF0000','AE00FF','BCA8E6','7E8D00','9D9
D96','00789B','FF4E00');

        $arr = array('ITEM','TEXTOS','ENTEROS','FECHAS','COLORES');
        $xls->OpenRow();
        foreach($arr as $cod=>$val)    $xls-
>NewCell($val,false,array('align'=>'center','background'=>'666666','color
'=>'FFFFFF','bold'=>true,'border'=>'000000'));
        $xls->CloseRow();

        for($i=0;$i<10;$i++){
                $xls->OpenRow();
                        $xls->NewCell($i+1,false,$xls_int);
                        $xls->NewCell($textos[$i],true,$xls_normal);
//Auto alineado
                        $xls->NewCell(rand(100,10000),false,$xls_int);
                        $xls-
>NewCell(date('d/m/Y',time()+24*60*60*$i),false,$xls_date);
                        $xls-
>NewCell(rand(100,10000),false,array('type'=>'int','width'=>'250','color'
=>$colores[rand(0,9)],'background'=>$colores[rand(0,9)],'border'=>'000000
'));
                $xls->CloseRow();
        }
        $xls->GetXLS();
?>




******************************************************___________**********



Pasos Para Elaborar Reporte En Excel:

   1. Se debe de descomprimir y copiar en una carpeta en la aplicacion que se este
      desarrollando, es recomendable crear una carpeta dentro de la aplicacionunicamente
      para las clases de PHPExcel.
   2. A continuacion el archivo php que lo coloque en un directorio distinto al de
      PHPExcel dentro de la aplicacion que al momento de ejecutarlo este crea el archivo
      excel dentro del directorio que se le asigno. A como pueden ver unicamente
      importamos el archivo PHPExcel y el componente para manipular archivos de
      Excel 2007. El script php que les muestro toma los datos de mysql para crear una
      hoja de calculo con estos. Ademas se utilizan colores de fondo para diferenciar el
      header de la hoja.



<?php
/** Error reporting */

error_reporting(E_ALL);



/** Include path **/

ini_set('include_path', ini_get('include_path').';../Classes/');



/** PHPExcel */

include '../excel/PHPExcel.php';



/** PHPExcel_Writer_Excel2007 */

include '../excel/PHPExcel/Writer/Excel2007.php';



// Create new PHPExcel object

echo date('H:i:s') . " Create new PHPExcel objectn";

$objPHPExcel = new PHPExcel();



// Set properties

echo date('H:i:s') . " Set propertiesn";

$objPHPExcel->getProperties()->setCreator("E-Tracking");

$objPHPExcel->getProperties()->setLastModifiedBy("E-Tracking");

$objPHPExcel->getProperties()->setTitle("Reporte De TarifasPorCategoria");

$objPHPExcel->getProperties()->setSubject("Reporte E-Tracking");

$objPHPExcel->getProperties()->setDescription("ReporteGeneradoPorSistema E-
Tracking");
// Add some data

echo date('H:i:s') . " Add some datan";

$objPHPExcel->setActiveSheetIndex(0);

$objPHPExcel->getActiveSheet()->SetCellValue('A1', 'REPORTE DE TARIFAS DE ' .
$_GET["ident"]);

$objPHPExcel->getActiveSheet()->SetCellValue('F1', 'FECHA DE REPORTE:');

$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(20);

$objPHPExcel->getActiveSheet()->SetCellValue('G1', date("d-m-Y"));



$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(30);

$objPHPExcel->getActiveSheet()->SetCellValue('C3','CATEGORIA' );

$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(25);

$objPHPExcel->getActiveSheet()->SetCellValue('D3', 'TARIFA POR KILOGRAMO');

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

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



$objPHPExcel->getActiveSheet()->getStyle('C3')->getFont()->setColor(new
PHPExcel_Style_Color( PHPExcel_Style_Color::COLOR_WHITE ) );

$objPHPExcel->getActiveSheet()->getStyle('D3')->getFont()->setColor(new
PHPExcel_Style_Color( PHPExcel_Style_Color::COLOR_WHITE ) );



$objPHPExcel->getActiveSheet()->getStyle('C3')->getFill()-
>setFillType(PHPExcel_Style_Fill::FILL_SOLID);

$objPHPExcel->getActiveSheet()->getStyle('C3')->getFill()->getStartColor()-
>setARGB(PHPExcel_Style_Color::COLOR_DARKGREEN);

$objPHPExcel->getActiveSheet()->getStyle('D3')->getFill()-
>setFillType(PHPExcel_Style_Fill::FILL_SOLID);

$objPHPExcel->getActiveSheet()->getStyle('D3')->getFill()->getStartColor()-
>setARGB(PHPExcel_Style_Color::COLOR_DARKGREEN);



include("../Conexion.php");

$conexion = new Conexion();

$c = $conexion->conectar();



$consulta = "SELECT UPPER(categorias_articulos.categoria), tarifas.tarifa FROM tarifas "
.

"INNER JOIN categorias_articulos ON categorias_articulos.idcategorias_articulos =
tarifas.idcategorias_articulos" .

" WHEREtarifas.flag = '0' AND tarifas.centros_acopio_idcentro_acopio = " .
$_GET["id_ident"];



$resultado_consulta = mysql_query($consulta);

$i = 5;

while ($registro = mysql_fetch_array($resultado_consulta))

{

$objPHPExcel->getActiveSheet()->SetCellValue('C' . $i, $registro[0]);

$objPHPExcel->getActiveSheet()->SetCellValue('D' . $i, $registro[1] . ' colones');

$i++;

}
// Rename sheet

echo date('H:i:s') . " Rename sheetn";

$objPHPExcel->getActiveSheet()->setTitle('REPORTE DE TARIFAS');




// Save Excel 2007 file

echo date('H:i:s') . " Writeto Excel2007 formatn";

$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
// Aqui se crea en el directorio el archivo con la identificacion del
//Usuario que lo creo y con el nombre propio del archivo
$objWriter->save($_GET["usuario"] . "ReporteDeTarifas.xlsx");



// Echo done

echo date('H:i:s') . " Done writing file.rn";

?>




Para Elaborar Un Reporte PDF

     1. Utilizar el paso 1 (descomprimir y copiar en la aplicacion) del ejemplo anterior.
     2. A continuacion les muestro el script que con los mismos datos del ejemplo anterior
        se crea un reporte en PDF, a diferencia del anterior este no crea el archivo, el
        servidor al procesar el script lo envia a la parte cliente(navegador) con cabecera http
        pdf con el que se puede descargar y observar:
<?php

/** Error reporting */

error_reporting(E_ALL);



/** Include path **/

ini_set('include_path', ini_get('include_path').';../Classes/');



/** PHPExcel */

include '../excel/PHPExcel.php';



/** PHPExcel_Writer_Excel2007 */

include '../excel/PHPExcel/Writer/Excel2007.php';



// Create new PHPExcel object



$objPHPExcel = new PHPExcel();



// Set properties



$objPHPExcel->getProperties()->setCreator("E-Tracking");

$objPHPExcel->getProperties()->setLastModifiedBy("E-Tracking");

$objPHPExcel->getProperties()->setTitle("Reporte De TarifasPorCategoria");
$objPHPExcel->getProperties()->setSubject("Reporte E-Tracking");

$objPHPExcel->getProperties()->setDescription("ReporteGeneradoPorSistema E-
Tracking");




// Add some data

$objPHPExcel->setActiveSheetIndex(0);



$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20);

$objPHPExcel->getActiveSheet()->SetCellValue('A1', 'REPORTE DE TARIFAS DE ' .
$_GET["ident"]);

$objPHPExcel->getActiveSheet()->SetCellValue('F1', 'FECHA DE REPORTE:');

$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(15);

$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(20);

$objPHPExcel->getActiveSheet()->SetCellValue('G1', date("d-m-Y"));



$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(30);

$objPHPExcel->getActiveSheet()->SetCellValue('C3','CATEGORIA' );

$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(25);

$objPHPExcel->getActiveSheet()->SetCellValue('D3', 'TARIFA POR KILOGRAMO');

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

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



$objPHPExcel->getActiveSheet()->getStyle('C3')->getFont()->setColor(new
PHPExcel_Style_Color( PHPExcel_Style_Color::COLOR_WHITE ) );
$objPHPExcel->getActiveSheet()->getStyle('D3')->getFont()->setColor(new
PHPExcel_Style_Color( PHPExcel_Style_Color::COLOR_WHITE ) );



$objPHPExcel->getActiveSheet()->getStyle('C3')->getFill()-
>setFillType(PHPExcel_Style_Fill::FILL_SOLID);

$objPHPExcel->getActiveSheet()->getStyle('C3')->getFill()->getStartColor()-
>setARGB(PHPExcel_Style_Color::COLOR_DARKGREEN);

$objPHPExcel->getActiveSheet()->getStyle('D3')->getFill()-
>setFillType(PHPExcel_Style_Fill::FILL_SOLID);

$objPHPExcel->getActiveSheet()->getStyle('D3')->getFill()->getStartColor()-
>setARGB(PHPExcel_Style_Color::COLOR_DARKGREEN);



include("../Conexion.php");

$conexion = new Conexion();

$c = $conexion->conectar();



$consulta = "SELECT UPPER(categorias_articulos.categoria), tarifas.tarifa FROM tarifas "
.

"INNER JOIN categorias_articulos ON categorias_articulos.idcategorias_articulos =
tarifas.idcategorias_articulos" .

" WHEREtarifas.flag = '0' AND tarifas.centros_acopio_idcentro_acopio = " .
$_GET["id_ident"];



$resultado_consulta = mysql_query($consulta);

$i = 5;

while ($registro = mysql_fetch_array($resultado_consulta))

{
$objPHPExcel->getActiveSheet()->SetCellValue('C' . $i, $registro[0]);

$objPHPExcel->getActiveSheet()->SetCellValue('D' . $i, $registro[1] . ' colones');

$i++;

}




// Rename sheet

$objPHPExcel->getActiveSheet()->setTitle('REPORTE DE TARIFAS');




// Save Excel 2007 file



// Redirect output to a client’s web browser (Excel2007)

header('Content-Type: application/pdf');

header('Content-Disposition: attachment;filename= "' . $_GET["usuario"] .
'ReporteDeTarifas.pdf"');

header('Cache-Control: max-age=0');



$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'PDF');

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



exit;
<?php
//Exportar datos de php a Excel
header("Content-Type: application/vnd.ms-excel");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("content-disposition: attachment;filename=Reportes.xls");
?>
<HTML LANG="es">
<TITLE>::.Exportacion de Datos .::</TITLE>
</head>
<body>
<?php
$NombreBD = "Tu_DB";
$Servidor = "localhost";
$Usuario = "root";
$Password ="";
$IdConexion = mysql_connect($Servidor, $Usuario, $Password);
mysql_select_db($NombreBD, $IdConexion);

$sql = "SELECT Apellido, Nombre, Dni, Domicilio FROM Excel";
$result=mysql_query($sql,$IdConexion);

?>

<TABLE BORDER=1 align="center" CELLPADDING=1 CELLSPACING=1>
<TR>
<TD>Apellido</TD>
<TD>Nombre</TD>
<TD>Dni</TD>
<TD>Domicilio</TD>

</TR>
<?php
while($row = mysql_fetch_array($result)) {
printf("<tr>
<td>&nbsp;%s</td>
<td>&nbsp;%s&nbsp;</td>
<td>&nbsp;%s</td>
<td>&nbsp;%s</td>
</tr>", $row["Apellido"],$row["Nombre"],$row["Dni"],$row["Domicilio"]);
}
mysql_free_result($result);
mysql_close($IdConexion); //Cierras la Conexión
?>
</table>
</body>
</html>



Esta línea de código nos permite exportar el resultado a Excel:
viewsourceprint?
1.header("Content-Type: application/vnd.ms-excel");

Podemos cambiar el nombre con el cual queremos guardar el xls:

viewsourceprint?
1.header("content-disposition: attachment;filename=Reportes.xls");

Armamos la conexion a la base de datos. Para probar localmente usamos el nombre de la
tabla, Usuario=root y Password=”". Si vamos a levantar en un servidor recordar cambiar
estos parametros.

viewsourceprint?
1.$NombreBD= "Tu_DB";
2.$Servidor= "localhost";
3.$Usuario= "root";
4.$Password="";
5.$IdConexion= mysql_connect($Servidor, $Usuario, $Password);
6.mysql_select_db($NombreBD, $IdConexion);

Ahora si, mediante un bucle while vamos mostrando los registros de nuestras tabla:

viewsourceprint?
01.<?php
02.while($row= mysql_fetch_array($result)) {
03.printf("<tr>
04.<td>&nbsp;%s</td>
05.<td>&nbsp;%s&nbsp;</td>
06.<td>&nbsp;%s</td>
07.<td>&nbsp;%s</td>
08.</tr>",
$row["Apellido"],$row["Nombre"],$row["Dni"],$row["Domicilio"]);
09.}
10.mysql_free_result($result);
11.mysql_close($IdConexion); //Cierras la Conexión
12.?>

Este código abre directamente Excel e inserta los registros, por lo que debemos valernos de
un enlace para dejarlo un poco más estético.
Espero les sea de utilidad, como lo fue para mí. Ante cualquier duda o sugerencia, dejanos
en los comentarios.
Saludos, cordiales.

Más contenido relacionado

La actualidad más candente

Microsoft access
Microsoft accessMicrosoft access
Microsoft accessReshmiSV
 
ADO.NET difference faqs compiled- 1
ADO.NET difference  faqs compiled- 1ADO.NET difference  faqs compiled- 1
ADO.NET difference faqs compiled- 1Umar Ali
 
Oracle Forms Creation
Oracle Forms CreationOracle Forms Creation
Oracle Forms CreationSekhar Byna
 
Images and Lists in HTML
Images and Lists in HTMLImages and Lists in HTML
Images and Lists in HTMLMarlon Jamera
 
Customizing job shop scheduling using microsoft dynamics ax part2 3
Customizing job shop scheduling using microsoft dynamics ax part2 3Customizing job shop scheduling using microsoft dynamics ax part2 3
Customizing job shop scheduling using microsoft dynamics ax part2 3Julien Lecadou,MSc.
 
Weblogic Administration Managed Server migration
Weblogic Administration Managed Server migrationWeblogic Administration Managed Server migration
Weblogic Administration Managed Server migrationRakesh Gujjarlapudi
 
Technical Overview of CDS View - SAP HANA Part II
Technical Overview of CDS View - SAP HANA Part IITechnical Overview of CDS View - SAP HANA Part II
Technical Overview of CDS View - SAP HANA Part IIAshish Saxena
 
Ms access basics ppt
Ms access basics ppt Ms access basics ppt
Ms access basics ppt vethics
 
Oracle Architecture
Oracle ArchitectureOracle Architecture
Oracle ArchitectureNeeraj Singh
 
Learn html Basics
Learn html BasicsLearn html Basics
Learn html BasicsMcSoftsis
 
Oracle 10g to 11g upgrade on sap(10.2.0.5.0 to 11.2.0.3)
Oracle 10g to 11g upgrade on sap(10.2.0.5.0 to 11.2.0.3)Oracle 10g to 11g upgrade on sap(10.2.0.5.0 to 11.2.0.3)
Oracle 10g to 11g upgrade on sap(10.2.0.5.0 to 11.2.0.3)yoonus ch
 
06.01 sql select distinct
06.01 sql select distinct06.01 sql select distinct
06.01 sql select distinctBishal Ghimire
 
Spreadsheets and Database Packages
Spreadsheets and Database PackagesSpreadsheets and Database Packages
Spreadsheets and Database PackagesSURBHI SAROHA
 
HTML Start Up - Introduction to HTML
HTML Start Up - Introduction to HTMLHTML Start Up - Introduction to HTML
HTML Start Up - Introduction to HTMLGrayzon Gonzales, LPT
 

La actualidad más candente (20)

Microsoft access
Microsoft accessMicrosoft access
Microsoft access
 
ADO.NET difference faqs compiled- 1
ADO.NET difference  faqs compiled- 1ADO.NET difference  faqs compiled- 1
ADO.NET difference faqs compiled- 1
 
Oracle Forms Creation
Oracle Forms CreationOracle Forms Creation
Oracle Forms Creation
 
Images and Lists in HTML
Images and Lists in HTMLImages and Lists in HTML
Images and Lists in HTML
 
Customizing job shop scheduling using microsoft dynamics ax part2 3
Customizing job shop scheduling using microsoft dynamics ax part2 3Customizing job shop scheduling using microsoft dynamics ax part2 3
Customizing job shop scheduling using microsoft dynamics ax part2 3
 
Weblogic Administration Managed Server migration
Weblogic Administration Managed Server migrationWeblogic Administration Managed Server migration
Weblogic Administration Managed Server migration
 
Technical Overview of CDS View - SAP HANA Part II
Technical Overview of CDS View - SAP HANA Part IITechnical Overview of CDS View - SAP HANA Part II
Technical Overview of CDS View - SAP HANA Part II
 
Ms access basics ppt
Ms access basics ppt Ms access basics ppt
Ms access basics ppt
 
Oracle Architecture
Oracle ArchitectureOracle Architecture
Oracle Architecture
 
Learning Html
Learning HtmlLearning Html
Learning Html
 
Learn html Basics
Learn html BasicsLearn html Basics
Learn html Basics
 
Advance HTML
Advance HTMLAdvance HTML
Advance HTML
 
Oracle 10g to 11g upgrade on sap(10.2.0.5.0 to 11.2.0.3)
Oracle 10g to 11g upgrade on sap(10.2.0.5.0 to 11.2.0.3)Oracle 10g to 11g upgrade on sap(10.2.0.5.0 to 11.2.0.3)
Oracle 10g to 11g upgrade on sap(10.2.0.5.0 to 11.2.0.3)
 
06.01 sql select distinct
06.01 sql select distinct06.01 sql select distinct
06.01 sql select distinct
 
Spreadsheets and Database Packages
Spreadsheets and Database PackagesSpreadsheets and Database Packages
Spreadsheets and Database Packages
 
HTML Start Up - Introduction to HTML
HTML Start Up - Introduction to HTMLHTML Start Up - Introduction to HTML
HTML Start Up - Introduction to HTML
 
Html introduction
Html introductionHtml introduction
Html introduction
 
MySQL for beginners
MySQL for beginnersMySQL for beginners
MySQL for beginners
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
MS ACCESS (REPORT)
MS ACCESS (REPORT)MS ACCESS (REPORT)
MS ACCESS (REPORT)
 

Similar a Php excel

Similar a Php excel (20)

Guia N5 Proyectos Web Consultas Php Y My Sql
Guia N5   Proyectos Web   Consultas Php Y My SqlGuia N5   Proyectos Web   Consultas Php Y My Sql
Guia N5 Proyectos Web Consultas Php Y My Sql
 
Jacqueline nuñez pacco
Jacqueline nuñez paccoJacqueline nuñez pacco
Jacqueline nuñez pacco
 
Jacqueline nuñez pacco
Jacqueline nuñez paccoJacqueline nuñez pacco
Jacqueline nuñez pacco
 
Documentacion jhon elvis_quispe_gutierrez
Documentacion jhon elvis_quispe_gutierrezDocumentacion jhon elvis_quispe_gutierrez
Documentacion jhon elvis_quispe_gutierrez
 
Wp config.php
Wp config.phpWp config.php
Wp config.php
 
Apuntes php
Apuntes phpApuntes php
Apuntes php
 
Ajax
AjaxAjax
Ajax
 
Documentacion
DocumentacionDocumentacion
Documentacion
 
Customizer: configurando un sitio en tiempo real
Customizer: configurando un sitio en tiempo realCustomizer: configurando un sitio en tiempo real
Customizer: configurando un sitio en tiempo real
 
Guía práctica desarrollo web con php 5 y my sql
Guía práctica desarrollo web con php 5 y my sqlGuía práctica desarrollo web con php 5 y my sql
Guía práctica desarrollo web con php 5 y my sql
 
Ejemplos de php_mysql
Ejemplos de php_mysqlEjemplos de php_mysql
Ejemplos de php_mysql
 
Gonzalo lopez miranda
Gonzalo lopez mirandaGonzalo lopez miranda
Gonzalo lopez miranda
 
tutorial de slide.com
tutorial de slide.comtutorial de slide.com
tutorial de slide.com
 
Php2
Php2 Php2
Php2
 
Funciones
FuncionesFunciones
Funciones
 
Informe grupal f_arinango_ cuenca
Informe grupal f_arinango_ cuencaInforme grupal f_arinango_ cuenca
Informe grupal f_arinango_ cuenca
 
EXAMEN
EXAMENEXAMEN
EXAMEN
 
Clases de php
Clases de phpClases de php
Clases de php
 
Julissa huaman hilari
Julissa huaman hilariJulissa huaman hilari
Julissa huaman hilari
 
Desarrollando aplicaciones web usando Catalyst y jQuery
Desarrollando aplicaciones web usando Catalyst y jQueryDesarrollando aplicaciones web usando Catalyst y jQuery
Desarrollando aplicaciones web usando Catalyst y jQuery
 

Php excel

  • 1. PHPExcel, libreria PHP para leer y escribir archivos de Excel 07-07-2008 Tutoriales, Programación, Desarrollo Web 49734 hits (100 %) 44 comentarios Creo que el título lo dice todo. Esta librería permite leer y manipular el contenido de una hoja de cálculo hecha con Microsoft Excel. Vamos directo al grano y veamos un ejemplo. Usaremos Microsoft Office Excel 2007 para la hoja de cálculo, ósea el archivo tendrá la extensión xlsx. También usaremos la versión 5.2.x de PHP. 1. Descargue la libreriaPHPExcel Descargamos la ultima versión. Después de descomprimirla ubicamos la carpeta Clases y la movemos a una carpeta donde pondremos nuestro ejemplo para este caso se llamará phpexcel_ejemplo. De tal manera que quede así: ruta_servidorphpexcel_ejemploClases. 2. Creamos un documentos de Excel La hoja de cálculo tendrá el siguiente formato: (descargar archivo de ejemplo). La ubicamos en la carpeta phpexcel_ejemplo. 3. Creamos la interfaz web Mediante HTML creamos una formulario para el ingreso de los valores, y también escribimos código para usar la librería PHPExcel. Este archio lo guardamos con el nombre de index.phpen la carpeta phpexcel_ejemplo. &nbsp;<?php /** Incluir la ruta **/ set_include_path(get_include_path() . PATH_SEPARATOR .'./Classes/'); /** Clasesnecesarias */ require_once('PHPExcel.php'); require_once('PHPExcel/Reader/Excel2007.php'); // Variables de la página $_VIEWDATA = array( 'v_precioTotal' => 0, 'v_descuento' => 0, 'v_precioFinal' => 0 ); // Petición de cálculo? if (isset($_REQUEST['boton_calcular'])) {
  • 2. // Cargando la hoja de cálculo $objReader = new PHPExcel_Reader_Excel2007(); $objPHPExcel = $objReader->load("calculo.xlsx"); // Asignarhoja de calculoactiva $objPHPExcel->setActiveSheetIndex(0); // Asignar data $objPHPExcel->getActiveSheet()->setCellValue('automatico', $_REQUEST['transmision_Automatica']); $objPHPExcel->getActiveSheet()->setCellValue('cuero', $_REQUEST['asientos_Cuero']); $objPHPExcel->getActiveSheet()->setCellValue('suspension', $_REQUEST['suspension']); // Calculos $_VIEWDATA['v_precioTotal'] = $objPHPExcel->getActiveSheet()- >getCell('total')->getCalculatedValue(); $_VIEWDATA['v_descuento'] = $objPHPExcel->getActiveSheet()- >getCell('descuento')->getCalculatedValue(); $_VIEWDATA['v_precioFinal'] = $objPHPExcel->getActiveSheet()- >getCell('final')->getCalculatedValue(); } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Ejemplo</title> </head> <body> <form id="formulario" method="post" name="formulario" action="index.php"> <table> <tr> <th>Transmisi&oacute;nautom&aacute;tica :</th> <td> <select id="transmision_Automatica" name="transmision_Automatica"> <?php if(isset($_REQUEST['transmision_Automatica'])) { ?> <option value="<?php echo $_REQUEST['transmision_Automatica']; ?>" selected="selected"><?php echo $_REQUEST['transmision_Automatica']; ?></option> <?php } ?> <optionvalue="No">No</option> <optionvalue="Si">Si</option> </select> </td> </tr> <tr> <th>Asientos de cuero:</th> <td> <select id="asientos_Cuero" name="asientos_Cuero">
  • 3. <?phpif(isset($_REQUEST['asientos_Cuero'])) { ?> <option value="<?php echo $_REQUEST['asientos_Cuero']; ?>" selected="selected"><?php echo $_REQUEST['asientos_Cuero']; ?></option> <?php } ?> <option value="No">No</option> <option value="Si">Si</option> </select> </td> </tr> <tr> <th>Suspensi&oacute;n:</th> <td> <select id="suspension" name="suspension"> <?php if(isset($_REQUEST['suspension'])) { ?> <option value="<?php echo $_REQUEST['suspension']; ?>" selected="selected"><?php echo $_REQUEST['suspension']; ?></option> <?php } ?> <option value="No">No</option> <option value="Si">Si</option> </select> </td> </tr> <tr> <th>&nbsp;</th> <td> <input id="boton_calcular" name="boton_calcular" type="submit" value="Calcular" /> </td> </tr> </table> </form> <?php if (isset($_REQUEST['boton_calcular'])) { ?> <h2>Detalles del Precio</h2> <p>Basado en tus preferencias, el precio de tu carro será S/. <?php echo number_format($_VIEWDATA['v_precioFinal'], 2); ?> Nuevos Soles.</p> <table> <tr> <th>Precio Total:</th> <td><?php echo number_format($_VIEWDATA['v_precioTotal'], 2); ?>Nuevos Soles</td> </tr> <tr> <th>Descuento:</th> <td><?php echo number_format($_VIEWDATA['v_descuento'] * 100, 2); ?>%</td> </tr> <tr> <td colspan="2"><hrnoshade="noshade"></hr> </tr> <tr> <th>Total Final:</th> <td><?php echo number_format($_VIEWDATA['v_precioFinal'], 2); ?>Nuevos Soles</td> </tr>
  • 4. </table> <p><a href="index.php">Calcular nuevo precio</a></p> <?php } ?> </body> </html> 4. A probar ...! Vamos al navegador web y escribirmoshttp://localhost/phpexcel_ejemplo/index.php y tendremos una interfaz con los datos que obtenemos de la hoja de cálculo. Seguramente se nos ocurrirá muchas cosas en la cual emplear está interesante librería. ¿Y que tal si la combinamos con AJAX?. La librería PHPExcel contiene documentación detallada para usarla correctamente, además de muchos otros ejemplos.
  • 5. PHPExcel is a collection of classes that allows you to generate excel documents in PHP. It is incredibly powerful and you can perform almost all (if not all) task that you would normally use in excel. It is really easy to install, either download the files or they now have a pear channel. For more details visit the PHPExcel site. This post is mainly for myself so that I can have a quick reference guide for common functions. For full documentation see PHPExcel Documentation. PHPExcel supports fluent interfaces so function calls can be chained together. The following: <?php $sheet->setCellValue("A1", "Text"); $sheet->setCellValue("A2", "Text"); $sheet->setCellValue("A3", "Text"); $sheet->setCellValue("A4", "Text"); $sheet->setCellValue("A5", "Text"); view rawNormal.phpThis Gist brought to you by GitHub. Can be written like: <?php $sheet->setCellValue("A1", "Text") ->setCellValue("A2", "Text") ->setCellValue("A3", "Text") ->setCellValue("A4", "Text") ->setCellValue("A5", "Text"); view rawFluentExample.phpThis Gist brought to you by GitHub. Basics Create a new object: $phpExcel = new PHPExcel(); Getting the active worksheet: $sheet = $phpExcel->getActiveSheet(); Add text to a cell: $sheet->setCellValue("A1", "Hello World"); Add a new worksheet: $sheet2 = $phpExcel->createSheet(); Add a formula to a cell: $sheet2->setCellValue("A5", "=SUM(A1:A4)"); Rename a worksheet: $sheet2->setTitle("Simple"); Merge cells: $sheet2()->mergeCells("A1:E3"); Unmerge cells: $sheet2()->unmergeCells("A1:E3"); Addingpropertiestoyour file Set Author: $phpExcel ->getProperties()->setCreator("Tom Smith"); Set Last Modified By: $phpExcel->getProperties()- >setLastModifiedBy("Tom Smith"); Set Title: $phpExcel->getProperties()->setTitle("Title"); Set Subject: $phpExcel->getProperties()->setSubject("Subject");
  • 6. Set Description: $phpExcel->getProperties()->setDescription("A description of the file."); Formatting A Cell Setting Width: $sheet2->getColumnDimension("A")->setWidth(40); Setting Auto Width: $sheet2->getColumnDimension("A")- >setAutoSize(true); Setting Text Alignment Right: $sheet2->getStyle("A1")->getAlignment()- >setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT); Making text of a range of cells bold: $sheet2->getStyle("A1:F1")- >applyFromArray(array("font" => array( "bold" => true))); Adding an auto filter to a range of cells: $sheet2->setAutoFilter("A1:C9"); Output to the browser as a download. <?php $phpExcel = new PHPExcel(); $phpExcel->getActiveSheet()->setTitle("My Sheet"); $phpExcel->setActiveSheetIndex(0); header("Content-Type: application/vnd.ms-excel"); header("Content-Disposition: attachment; filename="filename.xls""); header("Cache-Control: max-age=0"); $objWriter = PHPExcel_IOFactory::createWriter($phpExcel, "Excel5"); $objWriter->save("php://output"); exit; ****************************** EJEMPLO **** PHPExcel Code Example Posted on 8th April 2011 byTom Smith | <?php require_once("PHPExcel/PHPExcel.php"); $phpExcel=newPHPExcel(); $styleArray=array( 'font'=>array( 'bold'=>true, ) ); //Get the active sheet and assign to a variable $foo=$phpExcel->getActiveSheet(); //add column headers, set the title and make the text bold $foo->setCellValue("A1","Foo1")
  • 7. ->setCellValue("B1","Foo2") ->setCellValue("C1","Foo3") ->setCellValue("D1","Foo3") ->setTitle("Foo") ->getStyle("A1:D1")->applyFromArray($styleArray); //Create a new sheet $bar=$phpExcel->createSheet(); $bar->setCellValue("A1","Bar1") ->setCellValue("B1","Bar2") ->setCellValue("C1","Bar3") ->setCellValue("D1","Bar3") ->setTitle("Bar") ->getStyle("A1:D1")->applyFromArray($styleArray); //When in loops you always need to use a counter to ensure data goes into the next row. for($rowCounter=2;$rowCounter<20;$rowCounter++){ $foo->setCellValue("A$rowCounter","Row".($rowCounter-2)) ->setCellValue("B$rowCounter",$rowCounter*2) ->setCellValue("C$rowCounter",$rowCounter/2) - >setCellValue("D$rowCounter","=B$rowCounter+C$rowCounter"); $bar->setCellValue("A$rowCounter","Row".($rowCounter-2)) ->setCellValue("B$rowCounter",($rowCounter%2)?"Type 1":"Type2") ->setCellValue("C$rowCounter",str_repeat("foo ",rand(5,10))) ->setCellValue("D$rowCounter",str_repeat("% ",rand(20,50))); } //Merge the first two columns of the next row and sum columns C & D. $foo->mergeCells("A$rowCounter:B$rowCounter"); $foo->setCellValue("A$rowCounter","Total") ->setCellValue("C$rowCounter","=SUM(C2:C".($rowCounter-1).")") ->setCellValue("D$rowCounter","=SUM(D2:D".($rowCounter-1).")"); //Set the text alignment to right for the total cell. $foo->getStyle("A$rowCounter")->getAlignment()- >setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT); //Set the column widths $foo->getColumnDimension("A")->setWidth(40); $foo->getColumnDimension("B")->setWidth(20); $foo->getColumnDimension("C")->setWidth(20); $foo->getColumnDimension("D")->setWidth(20); $bar->getColumnDimension("A")->setAutoSize(true); $bar->getColumnDimension("B")->setAutoSize(true); $bar->getColumnDimension("C")->setAutoSize(true); $bar->getColumnDimension("D")->setWidth(40); //Wrap long fields $bar->getStyle("D1:D20")->getAlignment()->setWrapText(true);
  • 8. //Set the active sheet to the first sheet before outputting. This is only needed if you want to ensure the file is opened on the first sheet. $phpExcel->setActiveSheetIndex(0); //Output the generated excel file so that the user can save or open the file. header("Content-Type: application/vnd.ms-excel"); header("Content-Disposition: attachment; filename="example-excel- file.xls""); header("Cache-Control: max-age=0"); $objWriter=PHPExcel_IOFactory::createWriter($phpExcel,"Excel5"); $objWriter->save("php://output"); exit; ***********************¨¨¨¨¨¨¨¨¨¨¨¨¨¨************** 1.- DESCARGAR PHPExcel Lo primero que debemos hacer es descargarnos la última versión de esta librería en la página de descargas de PHPExcel y descomprimir el contenido en alguna carpeta de nuestro proyecto PHP. 2.- MODO DE USO Todas las librerías necesarias se encuentran en la carpeta Classes y debemos llamarlas con require_once(). Y podemos crear un archivo .php, por ejemplo un archivo excel.php: ? 1require_once("Classes/PHPExcel.php"); 2require_once("Classes/PHPExcel/Writer/Excel2007.php"); Luego creamos un OBJETO de la clase PHPExcel(): ? 1$objPHPExcel= newPHPExcel(); Por último trabajamos con varios metodos de PHPExcel para generar un Excel: ? 1 //algunos datos sobre autoría 2 $objPHPExcel->getProperties()->setCreator("autor"); $objPHPExcel->getProperties()->setLastModifiedBy("autor"); 3 $objPHPExcel->getProperties()->setTitle("titulo del Excel"); 4 $objPHPExcel->getProperties()->setSubject("Asunto"); 5 $objPHPExcel->getProperties()->setDescription("Descripcion"); 6 7 //Trabajamos con la hoja activa principal $objPHPExcel->setActiveSheetIndex(0); 8 9 //iteramos para los resultados 10foreach($filasas$row){ 11 $objPHPExcel->getActiveSheet()->SetCellValue("B".$row["id_cli"],
  • 9. 12$row["rut_cli"]); 13 $objPHPExcel->getActiveSheet()->SetCellValue("C".$row["id_cli"], $row["nombre_cli"]); 14 $objPHPExcel->getActiveSheet()->setCellValue("D".$row["id_cli"], 15$row["correo_cli"]); 16 $objPHPExcel->getActiveSheet()->setCellValue("E".$row["id_cli"], 17 $row["telefono_cli"]); $objPHPExcel->getActiveSheet()->setCellValue("F".$row["id_cli"], 18$row["pais_cli"]); 19} 20 21//Titulo del libro y seguridad 22$objPHPExcel->getActiveSheet()->setTitle('Reporte'); 23$objPHPExcel->getSecurity()->setLockWindows(true); $objPHPExcel->getSecurity()->setLockStructure(true); 24 25 26// Se modifican los encabezados del HTTP para indicar que se envia un 27archivo de Excel. 28header('Content-Type: application/vnd.openxmlformats- 29officedocument.spreadsheetml.sheet'); 30header('Content-Disposition: attachment;filename="reporteClientes.xlsx"'); 31header('Cache-Control: max-age=0'); 32 33//Creamos el Archivo .xlsx $objWriter= PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007'); $objWriter->save('php://output'); Con esto podemos crear un enlace al archivo excel.php para generar un reporte en excel: ? 1<ahref="excel.php">Exportar a Excel</a> Como ves, no es muy complicado crear archivos .xlsx. La documentación de esta gran librería es muy amplia y se puede jugar con el diseño del archivo, las formulas, etc.. ************************+ php-xcel-reader ************ <? include("class.excel.writer.php"); $xls = new ExcelWriter(); $xls_int = array('type'=>'int','border'=>'000000'); $xls_date = array('type'=>'date','border'=>'000000'); $xls_normal = array('border'=>'000000'); $textos = array('aaaabbbbccccddddd','bbbbaaaaadddd','ccccdsdsd','ddddasdfasdf','eee easdfasdfw','erwssd ds werwwe v ytjrhethwerwwejdrfgerwerwwekfghtrwerwwe','gggg','hhhh','iiii','kkkkkk');
  • 10. $colores = array('F17C0E','0012FF','06FF00','FF0000','AE00FF','BCA8E6','7E8D00','9D9 D96','00789B','FF4E00'); $arr = array('ITEM','TEXTOS','ENTEROS','FECHAS','COLORES'); $xls->OpenRow(); foreach($arr as $cod=>$val) $xls- >NewCell($val,false,array('align'=>'center','background'=>'666666','color '=>'FFFFFF','bold'=>true,'border'=>'000000')); $xls->CloseRow(); for($i=0;$i<10;$i++){ $xls->OpenRow(); $xls->NewCell($i+1,false,$xls_int); $xls->NewCell($textos[$i],true,$xls_normal); //Auto alineado $xls->NewCell(rand(100,10000),false,$xls_int); $xls- >NewCell(date('d/m/Y',time()+24*60*60*$i),false,$xls_date); $xls- >NewCell(rand(100,10000),false,array('type'=>'int','width'=>'250','color' =>$colores[rand(0,9)],'background'=>$colores[rand(0,9)],'border'=>'000000 ')); $xls->CloseRow(); } $xls->GetXLS(); ?> ******************************************************___________********** Pasos Para Elaborar Reporte En Excel: 1. Se debe de descomprimir y copiar en una carpeta en la aplicacion que se este desarrollando, es recomendable crear una carpeta dentro de la aplicacionunicamente para las clases de PHPExcel. 2. A continuacion el archivo php que lo coloque en un directorio distinto al de PHPExcel dentro de la aplicacion que al momento de ejecutarlo este crea el archivo excel dentro del directorio que se le asigno. A como pueden ver unicamente importamos el archivo PHPExcel y el componente para manipular archivos de Excel 2007. El script php que les muestro toma los datos de mysql para crear una hoja de calculo con estos. Ademas se utilizan colores de fondo para diferenciar el header de la hoja. <?php
  • 11. /** Error reporting */ error_reporting(E_ALL); /** Include path **/ ini_set('include_path', ini_get('include_path').';../Classes/'); /** PHPExcel */ include '../excel/PHPExcel.php'; /** PHPExcel_Writer_Excel2007 */ include '../excel/PHPExcel/Writer/Excel2007.php'; // Create new PHPExcel object echo date('H:i:s') . " Create new PHPExcel objectn"; $objPHPExcel = new PHPExcel(); // Set properties echo date('H:i:s') . " Set propertiesn"; $objPHPExcel->getProperties()->setCreator("E-Tracking"); $objPHPExcel->getProperties()->setLastModifiedBy("E-Tracking"); $objPHPExcel->getProperties()->setTitle("Reporte De TarifasPorCategoria"); $objPHPExcel->getProperties()->setSubject("Reporte E-Tracking"); $objPHPExcel->getProperties()->setDescription("ReporteGeneradoPorSistema E- Tracking");
  • 12. // Add some data echo date('H:i:s') . " Add some datan"; $objPHPExcel->setActiveSheetIndex(0); $objPHPExcel->getActiveSheet()->SetCellValue('A1', 'REPORTE DE TARIFAS DE ' . $_GET["ident"]); $objPHPExcel->getActiveSheet()->SetCellValue('F1', 'FECHA DE REPORTE:'); $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(20); $objPHPExcel->getActiveSheet()->SetCellValue('G1', date("d-m-Y")); $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(30); $objPHPExcel->getActiveSheet()->SetCellValue('C3','CATEGORIA' ); $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(25); $objPHPExcel->getActiveSheet()->SetCellValue('D3', 'TARIFA POR KILOGRAMO'); $objPHPExcel->getActiveSheet()->getStyle('C3')->getFont()->setBold(true); $objPHPExcel->getActiveSheet()->getStyle('D3')->getFont()->setBold(true); $objPHPExcel->getActiveSheet()->getStyle('C3')->getFont()->setColor(new PHPExcel_Style_Color( PHPExcel_Style_Color::COLOR_WHITE ) ); $objPHPExcel->getActiveSheet()->getStyle('D3')->getFont()->setColor(new PHPExcel_Style_Color( PHPExcel_Style_Color::COLOR_WHITE ) ); $objPHPExcel->getActiveSheet()->getStyle('C3')->getFill()- >setFillType(PHPExcel_Style_Fill::FILL_SOLID); $objPHPExcel->getActiveSheet()->getStyle('C3')->getFill()->getStartColor()-
  • 13. >setARGB(PHPExcel_Style_Color::COLOR_DARKGREEN); $objPHPExcel->getActiveSheet()->getStyle('D3')->getFill()- >setFillType(PHPExcel_Style_Fill::FILL_SOLID); $objPHPExcel->getActiveSheet()->getStyle('D3')->getFill()->getStartColor()- >setARGB(PHPExcel_Style_Color::COLOR_DARKGREEN); include("../Conexion.php"); $conexion = new Conexion(); $c = $conexion->conectar(); $consulta = "SELECT UPPER(categorias_articulos.categoria), tarifas.tarifa FROM tarifas " . "INNER JOIN categorias_articulos ON categorias_articulos.idcategorias_articulos = tarifas.idcategorias_articulos" . " WHEREtarifas.flag = '0' AND tarifas.centros_acopio_idcentro_acopio = " . $_GET["id_ident"]; $resultado_consulta = mysql_query($consulta); $i = 5; while ($registro = mysql_fetch_array($resultado_consulta)) { $objPHPExcel->getActiveSheet()->SetCellValue('C' . $i, $registro[0]); $objPHPExcel->getActiveSheet()->SetCellValue('D' . $i, $registro[1] . ' colones'); $i++; }
  • 14. // Rename sheet echo date('H:i:s') . " Rename sheetn"; $objPHPExcel->getActiveSheet()->setTitle('REPORTE DE TARIFAS'); // Save Excel 2007 file echo date('H:i:s') . " Writeto Excel2007 formatn"; $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel); // Aqui se crea en el directorio el archivo con la identificacion del //Usuario que lo creo y con el nombre propio del archivo $objWriter->save($_GET["usuario"] . "ReporteDeTarifas.xlsx"); // Echo done echo date('H:i:s') . " Done writing file.rn"; ?> Para Elaborar Un Reporte PDF 1. Utilizar el paso 1 (descomprimir y copiar en la aplicacion) del ejemplo anterior. 2. A continuacion les muestro el script que con los mismos datos del ejemplo anterior se crea un reporte en PDF, a diferencia del anterior este no crea el archivo, el servidor al procesar el script lo envia a la parte cliente(navegador) con cabecera http pdf con el que se puede descargar y observar:
  • 15. <?php /** Error reporting */ error_reporting(E_ALL); /** Include path **/ ini_set('include_path', ini_get('include_path').';../Classes/'); /** PHPExcel */ include '../excel/PHPExcel.php'; /** PHPExcel_Writer_Excel2007 */ include '../excel/PHPExcel/Writer/Excel2007.php'; // Create new PHPExcel object $objPHPExcel = new PHPExcel(); // Set properties $objPHPExcel->getProperties()->setCreator("E-Tracking"); $objPHPExcel->getProperties()->setLastModifiedBy("E-Tracking"); $objPHPExcel->getProperties()->setTitle("Reporte De TarifasPorCategoria");
  • 16. $objPHPExcel->getProperties()->setSubject("Reporte E-Tracking"); $objPHPExcel->getProperties()->setDescription("ReporteGeneradoPorSistema E- Tracking"); // Add some data $objPHPExcel->setActiveSheetIndex(0); $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20); $objPHPExcel->getActiveSheet()->SetCellValue('A1', 'REPORTE DE TARIFAS DE ' . $_GET["ident"]); $objPHPExcel->getActiveSheet()->SetCellValue('F1', 'FECHA DE REPORTE:'); $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(15); $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(20); $objPHPExcel->getActiveSheet()->SetCellValue('G1', date("d-m-Y")); $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(30); $objPHPExcel->getActiveSheet()->SetCellValue('C3','CATEGORIA' ); $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(25); $objPHPExcel->getActiveSheet()->SetCellValue('D3', 'TARIFA POR KILOGRAMO'); $objPHPExcel->getActiveSheet()->getStyle('C3')->getFont()->setBold(true); $objPHPExcel->getActiveSheet()->getStyle('D3')->getFont()->setBold(true); $objPHPExcel->getActiveSheet()->getStyle('C3')->getFont()->setColor(new PHPExcel_Style_Color( PHPExcel_Style_Color::COLOR_WHITE ) );
  • 17. $objPHPExcel->getActiveSheet()->getStyle('D3')->getFont()->setColor(new PHPExcel_Style_Color( PHPExcel_Style_Color::COLOR_WHITE ) ); $objPHPExcel->getActiveSheet()->getStyle('C3')->getFill()- >setFillType(PHPExcel_Style_Fill::FILL_SOLID); $objPHPExcel->getActiveSheet()->getStyle('C3')->getFill()->getStartColor()- >setARGB(PHPExcel_Style_Color::COLOR_DARKGREEN); $objPHPExcel->getActiveSheet()->getStyle('D3')->getFill()- >setFillType(PHPExcel_Style_Fill::FILL_SOLID); $objPHPExcel->getActiveSheet()->getStyle('D3')->getFill()->getStartColor()- >setARGB(PHPExcel_Style_Color::COLOR_DARKGREEN); include("../Conexion.php"); $conexion = new Conexion(); $c = $conexion->conectar(); $consulta = "SELECT UPPER(categorias_articulos.categoria), tarifas.tarifa FROM tarifas " . "INNER JOIN categorias_articulos ON categorias_articulos.idcategorias_articulos = tarifas.idcategorias_articulos" . " WHEREtarifas.flag = '0' AND tarifas.centros_acopio_idcentro_acopio = " . $_GET["id_ident"]; $resultado_consulta = mysql_query($consulta); $i = 5; while ($registro = mysql_fetch_array($resultado_consulta)) {
  • 18. $objPHPExcel->getActiveSheet()->SetCellValue('C' . $i, $registro[0]); $objPHPExcel->getActiveSheet()->SetCellValue('D' . $i, $registro[1] . ' colones'); $i++; } // Rename sheet $objPHPExcel->getActiveSheet()->setTitle('REPORTE DE TARIFAS'); // Save Excel 2007 file // Redirect output to a client’s web browser (Excel2007) header('Content-Type: application/pdf'); header('Content-Disposition: attachment;filename= "' . $_GET["usuario"] . 'ReporteDeTarifas.pdf"'); header('Cache-Control: max-age=0'); $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'PDF'); $objWriter->save('php://output'); exit;
  • 19. <?php //Exportar datos de php a Excel header("Content-Type: application/vnd.ms-excel"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("content-disposition: attachment;filename=Reportes.xls"); ?> <HTML LANG="es"> <TITLE>::.Exportacion de Datos .::</TITLE> </head> <body> <?php $NombreBD = "Tu_DB"; $Servidor = "localhost"; $Usuario = "root"; $Password =""; $IdConexion = mysql_connect($Servidor, $Usuario, $Password); mysql_select_db($NombreBD, $IdConexion); $sql = "SELECT Apellido, Nombre, Dni, Domicilio FROM Excel"; $result=mysql_query($sql,$IdConexion); ?> <TABLE BORDER=1 align="center" CELLPADDING=1 CELLSPACING=1> <TR> <TD>Apellido</TD> <TD>Nombre</TD> <TD>Dni</TD> <TD>Domicilio</TD> </TR> <?php while($row = mysql_fetch_array($result)) { printf("<tr> <td>&nbsp;%s</td> <td>&nbsp;%s&nbsp;</td> <td>&nbsp;%s</td> <td>&nbsp;%s</td> </tr>", $row["Apellido"],$row["Nombre"],$row["Dni"],$row["Domicilio"]); } mysql_free_result($result); mysql_close($IdConexion); //Cierras la Conexión ?> </table> </body> </html> Esta línea de código nos permite exportar el resultado a Excel:
  • 20. viewsourceprint? 1.header("Content-Type: application/vnd.ms-excel"); Podemos cambiar el nombre con el cual queremos guardar el xls: viewsourceprint? 1.header("content-disposition: attachment;filename=Reportes.xls"); Armamos la conexion a la base de datos. Para probar localmente usamos el nombre de la tabla, Usuario=root y Password=”". Si vamos a levantar en un servidor recordar cambiar estos parametros. viewsourceprint? 1.$NombreBD= "Tu_DB"; 2.$Servidor= "localhost"; 3.$Usuario= "root"; 4.$Password=""; 5.$IdConexion= mysql_connect($Servidor, $Usuario, $Password); 6.mysql_select_db($NombreBD, $IdConexion); Ahora si, mediante un bucle while vamos mostrando los registros de nuestras tabla: viewsourceprint? 01.<?php 02.while($row= mysql_fetch_array($result)) { 03.printf("<tr> 04.<td>&nbsp;%s</td> 05.<td>&nbsp;%s&nbsp;</td> 06.<td>&nbsp;%s</td> 07.<td>&nbsp;%s</td> 08.</tr>", $row["Apellido"],$row["Nombre"],$row["Dni"],$row["Domicilio"]); 09.} 10.mysql_free_result($result); 11.mysql_close($IdConexion); //Cierras la Conexión 12.?> Este código abre directamente Excel e inserta los registros, por lo que debemos valernos de un enlace para dejarlo un poco más estético. Espero les sea de utilidad, como lo fue para mí. Ante cualquier duda o sugerencia, dejanos en los comentarios. Saludos, cordiales.