Foros del Web » Programando para Internet » PHP »

[APORTE] Convertir Excel a un Array

Estas en el tema de [APORTE] Convertir Excel a un Array en el foro de PHP en Foros del Web. Les dejo una clase que sirve para convertir un archivo Excel en un arreglo que podremos manipular. Si bien no deberían ir en esta clase ...
  #1 (permalink)  
Antiguo 20/10/2012, 15:36
Avatar de portalmana  
Fecha de Ingreso: septiembre-2007
Ubicación: Montevideo-Uruguay
Mensajes: 633
Antigüedad: 16 años, 6 meses
Puntos: 80
Información [APORTE] Convertir Excel a un Array

Les dejo una clase que sirve para convertir un archivo Excel en un arreglo que podremos manipular.
Si bien no deberían ir en esta clase la parte de manejos de Arreglos se los dejo aqui para que tengan una mejor idea de como se puede utilizar.

Consideraciones:
Tener en cuenta que como carga el Excel a un Arreglo no es recomendable para archivos excel de muchos datos.
Los datos deben comenzar en la Columna A – Fila 1
El archivo excel deberá contener en la primera fila los encabezados o títulos y de ser posible se deberá otorgar una columnas en donde sus datos sean únicos (no se repitan), que serán usados como claves.
La mas importante de todas es que hace uso de la Libreria PHPExcel de Codeplex, por lo cual deberan hacer los requiere correspondientes.

Ahora un poco de codigo:
Código PHP:
Ver original
  1. <?php
  2. // Lanza todos los errores
  3. error_reporting(E_ALL  | E_STRICT);
  4. // Tiempo ilimitado para el script
  5.  
  6. require_once 'PHPExcel/Classes/PHPExcel.php';
  7. require_once 'PHPExcel/Classes/PHPExcel/IOFactory.php';
  8.  
  9. class ExcelToArray
  10. {
  11.     /**
  12.      * Contiene Las Extenciones Permitidas para Excel.
  13.      * @var Array
  14.      */
  15.     private $_tipoExcel = array('xlsx'  => 'Excel2007',
  16.                                 'xls'   => 'Excel5');
  17.    
  18.     /**
  19.      * Contiene la Cantidad de Columnas del Archivo Excel.
  20.      * @var integer
  21.      */
  22.     private $_columnas  = 0;
  23.    
  24.     /**
  25.      * Contiene la Cantidad de Filas del Archivo Excel.
  26.      * @var integer
  27.      */
  28.     private $_filas     = 0;
  29.    
  30.     /**
  31.      * Contiene el Titulo que sera el Identificador.
  32.      * @var string
  33.      */
  34.     private $_id;
  35.    
  36.     /**
  37.      * Contiene el Arreglo Generado a partir del Excel.
  38.      * @var array
  39.      */
  40.     private $_excel     = array();
  41.    
  42.     /**
  43.      * Contiene los Encabezados del Archivo Excel.
  44.      * @var array
  45.      */
  46.     private $_titulos   = array();
  47.    
  48.     /**
  49.      * Contiene la ruta y nombre del Archivo.
  50.      * @var type
  51.      */
  52.     private $_file;
  53.    
  54.     /**
  55.      * Contiene el Tipo del Archivo Excel para PHPExcel.
  56.      * @var string
  57.      */
  58.     private $_tipoPHPExcel;
  59.    
  60.     /**
  61.      * Constructor de Clase.
  62.      * @param   string  $file   Ruta y nombre del Archivo.
  63.      * @throws  Exception       Lanza exepcion si el archivo no existe o si,
  64.      *                          no es de una extencion valida.
  65.      */
  66.     public function __construct($file)
  67.     {
  68.         if (!file_exists($file)) {
  69.             throw new Exception('Error : El archivo no pudo ser Encontrado');
  70.         }
  71.        
  72.         $this->_file= $file;
  73.         $ext        = substr(strrchr($file, '.'), 1);
  74.        
  75.         if (!isset($this->_tipoExcel[$ext])) {
  76.             throw new Exception('Error : El archivo no es de un tipo Valido');
  77.         }
  78.         $this->_tipoPHPExcel    = $this->_tipoExcel[$ext];
  79.        
  80.     }
  81.  
  82.     /**
  83.      * Carga la Hoja Excel y Retorna el Arreglo.
  84.      * @param string $id    Contiene el nombre del encabezado que sera tomado como Id.
  85.      *                      Si no se proporciona o no existe sera la primera columnas.
  86.      * @return array
  87.      */
  88.     public function loadExcel($id = '')
  89.     {
  90.         // Creo un objeto de Lectura con el tipo de Archivo Correcto Excel20007(xlsx), Excel5(xls)
  91.         $objReader  = PHPExcel_IOFactory::createReader($this->_tipoPHPExcel);
  92.         // Configuro que sera solo para leer el archivo
  93.         $objReader  ->setReadDataOnly(true);
  94.         // Cargo el Archivo
  95.         $objPHPExcel    = $objReader->load($this->_file);
  96.         $objWorksheet   = $objPHPExcel->getActiveSheet();
  97.         $this->_columnas= PHPExcel_Cell::columnIndexFromString($objWorksheet->getHighestColumn());
  98.         $this->_filas   = $objWorksheet->getHighestRow();
  99.    
  100.         // Extraigo los Titulos
  101.         for ($i=0; $i<= $this->_columnas-1; $i++) {
  102.             $this->_titulos[$i] = $objWorksheet->getCellByColumnAndRow($i, 1)->getCalculatedValue();
  103.         }
  104.         // Verifica el Campo Identificador
  105.         $this->_id      = (in_array($id, $this->_titulos))? $id : $this->_titulos[0];
  106.        
  107.         // Levanto todos los Datos
  108.         for ($fila = 2; $fila <= $this->_filas; $fila++) {
  109.             $dFilas = array();
  110.             for ($columna = 0; $columna <= $this->_columnas-1; $columna++) {
  111.                 $dFilas[$this->_titulos[$columna]] =
  112.                         $objWorksheet->getCellByColumnAndRow($columna, $fila)->getCalculatedValue();
  113.             }
  114.             $this->_excel[$dFilas[$this->_id]] = $dFilas;
  115.         }
  116.        
  117.         return $this->_excel;
  118.     }
  119.    
  120.     /**
  121.      * Retorna el Campo seleccionado como Identificador.
  122.      * @return string
  123.      */
  124.     public function getId()
  125.     {
  126.         return $this->_id;
  127.     }
  128.    
  129.     /**
  130.      * Retorna la Cantidad de Columnas del Archivo Excel.
  131.      * @return integer
  132.      */
  133.     public function countColumns()
  134.     {
  135.         return $this->_columnas;
  136.     }
  137.    
  138.     /**
  139.      * Retorna la Cantidad de Filas del Archivo Excel.
  140.      * @return integer
  141.      */
  142.     public function countRows()
  143.     {
  144.         return $this->_filas;
  145.     }
  146.    
  147.     /**
  148.      * Retorna si una Columna Existe o no.
  149.      * @param   string  $nombreColumna  Nombre de la columna.
  150.      * @return  boolean
  151.      */
  152.     public function isColumn($nombreColumna)
  153.     {
  154.         return isset($this->_titulos[$nombreColumna]);
  155.     }
  156.    
  157.     /**
  158.      * Retorna el Arreglo Generado.
  159.      * @return array
  160.      */
  161.     public function getArray()
  162.     {
  163.         return $this->_excel;
  164.     }
  165.    
  166.     /**
  167.      * Retorna el registro para el id establecido.
  168.      * @param   string  $id     Nombre del Identificador.
  169.      * @return  array
  170.      */
  171.     public function findId($id)
  172.     {
  173.         $retorno    = false;
  174.         if (isset($this->_excel[$id])) {
  175.             $retorno = $this->_excel[$id];
  176.         }
  177.        
  178.         return $retorno;
  179.     }
  180.    
  181.     /**
  182.      * Retorna un arreglo con el valor buscado en la columna indicada.
  183.      * Busqueda Exacta.
  184.      * @param   string  $titulo     Titulo de la Columna
  185.      * @param   string  $valor      Valor a buscar
  186.      * @return  array
  187.      */
  188.     public function findByColumn($titulo, $valor)
  189.     {
  190.        return $this->_search($this->_excel, $titulo, $valor);
  191.     }
  192.    
  193.     /**
  194.      * Extraida de :
  195.      * @link http://php.net/manual/es/function.array-search.php
  196.      */
  197.     private function _search($array, $key, $value)
  198.     {
  199.         $results = array();
  200.         if (is_array($array)) {
  201.             if (isset($array[$key]) && $array[$key] == $value ) {
  202.                 $results[] = $array;
  203.             }  
  204.             foreach ($array as $subarray) {
  205.                 $results = array_merge($results, $this->_search($subarray, $key, $value));
  206.             }  
  207.         }
  208.         return $results;
  209.     }  
  210.  
  211.     /**
  212.      * Retorna un arreglo con el valor buscado en la columna indicada o no y la cantidad
  213.      * de veces que aparece el valor en las columnas si no se indica la misma.
  214.      * La busqueda es por valor aproximado.
  215.      * @param   string  $buscar     Valor a Buscar
  216.      * @param   string  $calve      Titulo de La columna donde se buscara o nada por Cualquiera.
  217.      * @return  array
  218.      */
  219.     public function findByCount($buscar, $titulo = null)
  220.     {
  221.         return $this->_recursiveArraySearchAll($this->_excel, $buscar, $titulo);
  222.     }
  223.    
  224.     /**
  225.      * Extraida de :
  226.      * @link http://php.net/manual/es/function.array-search.php
  227.      */        
  228.     private function _recursiveArraySearchAll($haystack, $needle, $index = null)
  229.     {
  230.         $arrIterator    = new RecursiveArrayIterator($haystack);
  231.         $recIterator    = new RecursiveIteratorIterator($arrIterator);
  232.         $resultkeys     = array();
  233.                      
  234.         while($recIterator->valid()) {
  235.             if (!is_array($recIterator->current())) {
  236.                 if ((isset($index) AND $recIterator->key() == $index  AND strpos($recIterator->current(), $needle) !== false )
  237.                     OR (!isset($index) AND strpos($recIterator->current(), $needle) !== false)) {
  238.                    
  239.                     $resultkeys[$arrIterator->key()] = isset($resultkeys[$arrIterator->key()])?  $resultkeys[$arrIterator->key()] + 1 : 1;
  240.                 }
  241.             }            
  242.             $recIterator->next();
  243.         }
  244.         arsort($resultkeys);
  245.         return $resultkeys;              
  246.     }    
  247.    
  248.    
  249.     /**
  250.      * Metodo ordenar.
  251.      * Ordena los resultados de acuerdo a la clave elegida.
  252.      * @param   string  $clave  Clave por la cual se quiere ordenar(titulo de columna).
  253.      * @param   boolean $asc    true para ascendente, false para descendente.
  254.      * @return  array
  255.      */
  256.     public function sort($campo = 'name', $asc = true)
  257.     {
  258.         if (empty($this->_excel)) {
  259.             throw new Exception('Primero debe usar la funcion loadExcel');
  260.         }
  261.  
  262.         $ordenarPor = (in_array($campo, $this->_titulos))? $campo : $this->_id;
  263.         $ascDesc    = ($asc)? SORT_ASC : SORT_DESC;
  264.         $caracter   = 0;
  265.  
  266.         foreach ($this->_excel as $ordenado) {
  267.             $tmpArray[] = $ordenado[$ordenarPor];
  268.             $caracter   = is_string($ordenado[$ordenarPor])? $caracter+1 : $caracter;
  269.         }
  270.        
  271.         $numero     = ($caracter)? SORT_STRING : SORT_NUMERIC;
  272.  
  273.         array_multisort($tmpArray, $ascDesc, $numero, $this->_excel);
  274.         return $this->_excel;
  275.     }      
  276. }
__________________
"La imaginación es más importante que el conocimiento. El conocimiento es limitado, mientras que la imaginación no" -- A.Einstein
objetivophp.com,twitter.com/objetivophp
  #2 (permalink)  
Antiguo 20/10/2012, 15:51
Avatar de portalmana  
Fecha de Ingreso: septiembre-2007
Ubicación: Montevideo-Uruguay
Mensajes: 633
Antigüedad: 16 años, 6 meses
Puntos: 80
Respuesta: [APORTE] Convertir Excel a un Array

Uso de la Clase:

En la variable $file pondremos la ruta y nombre de archivo que queremos convertir en un arreglo.
Luego instanciamos la clase, y con el método loadExcel, cargamos el archivo. Como parametro le pasaremos el titulo de una columna que la tomara como.
Como siempre antes incluiremos la clase con requiere_once, include etc...
Código PHP:
Ver original
  1. $file       = './claves_2.xlsx';
  2. $objExcelArray   = new ExcelToArray($file);
  3. $usuarios = $objExcelArray ->loadExcel('usuario');
$usuarios contendra un arreglo del tipo:
Código HTML:
Ver original
  1. array(7) {
  2.   ["objetivophp"]=>
  3.   array(3) {
  4.     ["usuario"]=>
  5.     string(11) "objetivophp"
  6.     ["clave"]=>
  7.     string(16) "idudnbsakjdhasnd"
  8.     ["email"]=>
  9.     string(22) "[email protected]"
  10.   }
  11.   ["forosdelweb"]=>
  12.   array(3) {
  13.     ["usuario"]=>
  14.     string(11) "forosdelweb"
  15.     ["clave"]=>
  16.     string(12) "ipñshb65634"
  17.     ["email"]=>
  18.     string(15) "[email protected]"
  19.   }
  20.   ["otroUsuario"]=>
  21.   array(3) {
  22.     ["usuario"]=>
  23.     string(11) "otroUsuario"
  24.     ["clave"]=>
  25.     string(8) "uaso1596"
  26.     ["email"]=>
  27.     string(14) "[email protected]"
  28.   }
  29.   ["prueba"]=>
  30.   array(3) {
  31.     ["usuario"]=>
  32.     string(6) "prueba"
  33.     ["clave"]=>
  34.     string(8) "probando"
  35.     ["email"]=>
  36.     string(17) "[email protected]"
  37.   }
  38.   ["otro"]=>
  39.   array(3) {
  40.     ["usuario"]=>
  41.     string(4) "otro"
  42.     ["clave"]=>
  43.     string(9) "clavesasa"
  44.     ["email"]=>
  45.     NULL
  46.   }
  47.   ["nuevo"]=>
  48.   array(3) {
  49.     ["usuario"]=>
  50.     string(5) "nuevo"
  51.     ["clave"]=>
  52.     string(13) "sdlasldkañsd"
  53.     ["email"]=>
  54.     NULL
  55.   }
  56.   ["masUsuar"]=>
  57.   array(3) {
  58.     ["usuario"]=>
  59.     string(8) "masUsuar"
  60.     ["clave"]=>
  61.     string(10) "qwewqeweqw"
  62.     ["email"]=>
  63.     NULL
  64.   }
  65. }

Ahora veremos algunos métodos útiles.
Código PHP:
Ver original
  1. // Retorna el mismo arreglo que en loadExcel si no capturamos el retorno.
  2. $datos = $objExcelArray   ->getArray();
  3. // Ahora buscaremos un usuario por identificador
  4. $usuario =  $objExcelArray   ->findId('forosdelweb')

La variable $usuario contendrá un arreglo o false si no encontró nada.:
Código HTML:
Ver original
  1. array(3) {
  2.   ["usuario"]=>
  3.   string(11) "forosdelweb"
  4.   ["clave"]=>
  5.   string(12) "ipñshb65634"
  6.   ["email"]=>
  7.   string(15) "[email protected]"
  8. }

Continuo en el siguiente post...
__________________
"La imaginación es más importante que el conocimiento. El conocimiento es limitado, mientras que la imaginación no" -- A.Einstein
objetivophp.com,twitter.com/objetivophp
  #3 (permalink)  
Antiguo 20/10/2012, 16:03
Avatar de portalmana  
Fecha de Ingreso: septiembre-2007
Ubicación: Montevideo-Uruguay
Mensajes: 633
Antigüedad: 16 años, 6 meses
Puntos: 80
Respuesta: [APORTE] Convertir Excel a un Array

Podemos tambien ordenar por algún campo en concreto, le pasaremos el campo que querramos ordenar en este caso email y un booleano para ordenar ascendente (true) o descendente (false) por defecto asume ascendente.
Aquí como queremos ascendente no pasamos el segundo parámetro.
Código PHP:
Ver original
  1. $orden = $objExcelArray->sort('email');

Salida en variable orden sera un arreglo:
Código HTML:
Ver original
  1. array(7) {
  2.   ["masUsuar"]=>
  3.   array(3) {
  4.     ["usuario"]=>
  5.     string(8) "masUsuar"
  6.     ["clave"]=>
  7.     string(10) "qwewqeweqw"
  8.     ["email"]=>
  9.     string(10) "[email protected]"
  10.   }
  11.   ["forosdelweb"]=>
  12.   array(3) {
  13.     ["usuario"]=>
  14.     string(11) "forosdelweb"
  15.     ["clave"]=>
  16.     string(12) "ipñshb65634"
  17.     ["email"]=>
  18.     string(15) "[email protected]"
  19.   }
  20.   ["nuevo"]=>
  21.   array(3) {
  22.     ["usuario"]=>
  23.     string(5) "nuevo"
  24.     ["clave"]=>
  25.     string(13) "sdlasldkañsd"
  26.     ["email"]=>
  27.     string(16) "[email protected]"
  28.   }
  29.   ["objetivophp"]=>
  30.   array(3) {
  31.     ["usuario"]=>
  32.     string(11) "objetivophp"
  33.     ["clave"]=>
  34.     string(16) "idudnbsakjdhasnd"
  35.     ["email"]=>
  36.     string(22) "[email protected]"
  37.   }
  38.   ["otro"]=>
  39.   array(3) {
  40.     ["usuario"]=>
  41.     string(4) "otro"
  42.     ["clave"]=>
  43.     string(9) "clavesasa"
  44.     ["email"]=>
  45.     string(14) "[email protected]"
  46.   }
  47.   ["otroUsuario"]=>
  48.   array(3) {
  49.     ["usuario"]=>
  50.     string(11) "otroUsuario"
  51.     ["clave"]=>
  52.     string(8) "uaso1596"
  53.     ["email"]=>
  54.     string(14) "[email protected]"
  55.   }
  56.   ["prueba"]=>
  57.   array(3) {
  58.     ["usuario"]=>
  59.     string(6) "prueba"
  60.     ["clave"]=>
  61.     string(8) "probando"
  62.     ["email"]=>
  63.     string(17) "[email protected]"
  64.   }
  65. }

Si queremos una búsqueda exacta en una determinada columna usamos la funcion findByColumn, tendremos que pasarle dos parámetros la columna y el valor a buscar.
Código PHP:
Ver original
  1. $busqueda = $objExcelArray->findByColumn('email', 'objExcelArray')
El resultado en la Variable $busqueda:
Código HTML:
Ver original
  1. array(1) {
  2.   [0]=>
  3.   array(3) {
  4.     ["usuario"]=>
  5.     string(8) "masUsuar"
  6.     ["clave"]=>
  7.     string(10) "qwewqeweqw"
  8.     ["email"]=>
  9.     string(10) "[email protected]"
  10.   }
  11. }
Continua...
__________________
"La imaginación es más importante que el conocimiento. El conocimiento es limitado, mientras que la imaginación no" -- A.Einstein
objetivophp.com,twitter.com/objetivophp
  #4 (permalink)  
Antiguo 20/10/2012, 16:12
Avatar de portalmana  
Fecha de Ingreso: septiembre-2007
Ubicación: Montevideo-Uruguay
Mensajes: 633
Antigüedad: 16 años, 6 meses
Puntos: 80
Respuesta: [APORTE] Convertir Excel a un Array

Por ultimo, el método findByCount, que busca dentro de todas las columnas que contengan el valor a buscar, o sea es una búsqueda no exacta.
El método acepta 2 parámetros, el primero es el valor a buscar y es obligatorio y el segundo parámetro que es optativo es la columna donde se buscara en caso de no existir busca en todas las columnas.
Lo que no retonara sera un arreglo que como clave tendrá el identificador de columna y como valor en la cantidad de columnas que aparece.
Ej.: Buscaremos las filas que contengan ro
Código PHP:
Ver original
  1. $busqueda = $objExcelArray->findByCount('ro');
El arreglo estará compuesto por:
Código HTML:
Ver original
  1. array(4) {
  2.   ["forosdelweb"]=>
  3.   int(2)
  4.   ["otro"]=>
  5.   int(2)
  6.   ["prueba"]=>
  7.   int(1)
  8.   ["otroUsuario"]=>
  9.   int(1)
  10. }

Por ultimo el Formato del Excel utilizado:
Código HTML:
Ver original
  1. <tr>
  2. <td>usuario</td>
  3. <td>clave</td>
  4. <td>email</td>
  5. </tr>
  6. <tr>
  7. <td>objetivophp</td>
  8. <td>idudnbsakjdhasnd</td>
  9. </tr>
  10. <tr>
  11. <td>forosdelweb</td>
  12. <td>ipñshb65634</td>
  13. </tr>
  14. <tr>
  15. <td>otroUsuario</td>
  16. <td>uaso1596</td>
  17. </tr>
  18. <tr>
  19. <td>prueba</td>
  20. <td>probando</td>
  21. </tr>
  22. <tr>
  23. <td></td>
  24. <td></td>
  25. <td></td>
  26. </tr>
  27. <tr>
  28. <td>otro</td>
  29. <td>clavesasa</td>
  30. </tr>
  31. <tr>
  32. <td>nuevo</td>
  33. <td>sdlasldkañsd</td>
  34. </tr>
  35. <tr>
  36. <td>masUsuar</td>
  37. <td>qwewqeweqw</td>
  38. </tr>

Saludos y espero que les sea de utilidad
__________________
"La imaginación es más importante que el conocimiento. El conocimiento es limitado, mientras que la imaginación no" -- A.Einstein
objetivophp.com,twitter.com/objetivophp
  #5 (permalink)  
Antiguo 20/10/2012, 16:17
Avatar de rodrigo791  
Fecha de Ingreso: noviembre-2009
Ubicación: Uruguay
Mensajes: 1.339
Antigüedad: 14 años, 5 meses
Puntos: 168
Respuesta: [APORTE] Convertir Excel a un Array

Ajam, interesante, tal vez algún día la utilice, buen aporte yoruga , +1
  #6 (permalink)  
Antiguo 20/10/2012, 16:19
Avatar de portalmana  
Fecha de Ingreso: septiembre-2007
Ubicación: Montevideo-Uruguay
Mensajes: 633
Antigüedad: 16 años, 6 meses
Puntos: 80
Respuesta: [APORTE] Convertir Excel a un Array

Cita:
Iniciado por rodrigo791 Ver Mensaje
Ajam, interesante, tal vez algún día la utilice, buen aporte yoruga , +1
Gracias compatriota...
__________________
"La imaginación es más importante que el conocimiento. El conocimiento es limitado, mientras que la imaginación no" -- A.Einstein
objetivophp.com,twitter.com/objetivophp
  #7 (permalink)  
Antiguo 20/10/2012, 18:13
Avatar de portalmana  
Fecha de Ingreso: septiembre-2007
Ubicación: Montevideo-Uruguay
Mensajes: 633
Antigüedad: 16 años, 6 meses
Puntos: 80
Respuesta: [APORTE] Convertir Excel a un Array

Actualización con 2 métodos nuevos que pueden resultar útiles.
Código PHP:
Ver original
  1. // Busca un Valor en el arreglo pasando como parametro una referencia tipo
  2. // Excel A1.
  3. valueCellFromArray($celda);
  4.  
  5. // Esta otra que busca directamente sobre el Excel
  6. getValueCellFromExcel($celda);
Algunos cambios también en la clase.
Código PHP:
Ver original
  1. <?php
  2. // Lanza todos los errores
  3. error_reporting(E_ALL  | E_STRICT);
  4. // Tiempo ilimitado para el script
  5.  
  6. require_once 'PHPExcel/Classes/PHPExcel.php';
  7. require_once 'PHPExcel/Classes/PHPExcel/IOFactory.php';
  8.  
  9. class ExcelToArray
  10. {
  11.     private $_tipoExcel = array('xlsx'  => 'Excel2007',
  12.                                 'xls'   => 'Excel5');
  13.    
  14.     private $_columnas  = 0;
  15.    
  16.     private $_filas     = 0;
  17.    
  18.     private $_id;
  19.    
  20.     private $_excel     = array();
  21.    
  22.     private $_titulos   = array();
  23.    
  24.     private $_file;
  25.    
  26.     private $_tipoPHPExcel;
  27.    
  28.     private $_objWorksheet;
  29.  
  30.     public function __construct($file)
  31.     {
  32.         if (!file_exists($file)) {
  33.             throw new Exception('Error : El archivo no pudo ser Encontrado');
  34.         }
  35.        
  36.         $this->_file= $file;
  37.         $ext        = substr(strrchr($file, '.'), 1);
  38.        
  39.         if (!isset($this->_tipoExcel[$ext])) {
  40.             throw new Exception('Error : El archivo no es de un tipo Valido');
  41.         }
  42.         $this->_tipoPHPExcel    = $this->_tipoExcel[$ext];
  43.        
  44.     }
  45.  
  46.     public function loadExcel($id = '')
  47.     {
  48.         $this->_createObjWorksheet();
  49.         // Extraigo los Titulos
  50.         for ($i=0; $i<= $this->_columnas-1; $i++) {
  51.             $this->_titulos[$i] = $this->_objWorksheet->getCellByColumnAndRow($i, 1)->getCalculatedValue();
  52.         }
  53.         // Verifica el Campo Identificador
  54.         $this->_id      = (in_array($id, $this->_titulos))? $id : $this->_titulos[0];
  55.        
  56.         // Levanto todos los Datos
  57.         for ($fila = 2; $fila <= $this->_filas; $fila++) {
  58.             $dFilas = array();
  59.             for ($columna = 0; $columna <= $this->_columnas-1; $columna++) {
  60.                 $dFilas[$this->_titulos[$columna]] =
  61.                         $this->_objWorksheet->getCellByColumnAndRow($columna, $fila)->getCalculatedValue();
  62.             }
  63.             $this->_excel[$dFilas[$this->_id]] = $dFilas;
  64.         }
  65.        
  66.         return $this->_excel;
  67.     }
  68.    
  69.     /**
  70.      * Metodo Privado que crea el Objeto WorkSheet.
  71.      * @return PHPExcel_Worksheet
  72.      */
  73.     private function _createObjWorksheet()
  74.     {
  75.        
  76.         if (!$this->_objWorksheet instanceof  PHPExcel_Worksheet) {
  77.             // Creo un objeto de Lectura con el tipo de Archivo Correcto Excel20007(xlsx), Excel5(xls)
  78.             $objReader  = PHPExcel_IOFactory::createReader($this->_tipoPHPExcel);
  79.             // Configuro que sera solo para leer el archivo
  80.             $objReader  ->setReadDataOnly(true);
  81.             // Cargo el Archivo
  82.             $objPHPExcel            = $objReader->load($this->_file);
  83.             $this->_objWorksheet    = $objPHPExcel->getActiveSheet();
  84.             $this->_columnas        = PHPExcel_Cell::columnIndexFromString($this->_objWorksheet->getHighestColumn());
  85.             $this->_filas           = $this->_objWorksheet->getHighestRow();            
  86.         }
  87.         return $this->_objWorksheet;
  88.     }
  89.  
  90.     public function getId()
  91.     {
  92.         return $this->_id;
  93.     }
  94.    
  95.     public function countColumns()
  96.     {
  97.         return $this->_columnas;
  98.     }
  99.    
  100.     public function countRows()
  101.     {
  102.         return $this->_filas;
  103.     }
  104.    
  105.     /**
  106.      * Retorna si una Columna Existe o no.
  107.      * @param   string  $nombreColumna  Nombre de la columna.
  108.      * @return  boolean
  109.      */
  110.     public function isColumn($nombreColumna)
  111.     {
  112.         return isset($this->_titulos[$nombreColumna]);
  113.     }
  114.    
  115.     /**
  116.      * Retorna el Arreglo Generado.
  117.      * @return array
  118.      */
  119.     public function getArray()
  120.     {
  121.         return $this->_excel;
  122.     }
  123.    
  124.     /**
  125.      * Retorna los Titulos del Archivo Excel.
  126.      * @return array
  127.      */
  128.     public function getTitulos()
  129.     {
  130.         return $this->_titulos;
  131.     }
  132.    
  133.     /**
  134.      * Retorna el registro para el id establecido.
  135.      * @param   string  $id     Nombre del Identificador.
  136.      * @return  array
  137.      */
  138.     public function findId($id)
  139.     {
  140.         $retorno    = false;
  141.         if (isset($this->_excel[$id])) {
  142.             $retorno = $this->_excel[$id];
  143.         }
  144.        
  145.         return $retorno;
  146.     }
  147.    
  148.     /**
  149.      * Retorna un arreglo con el valor buscado en la columna indicada.
  150.      * Busqueda Exacta.
  151.      * @param   string  $titulo     Titulo de la Columna
  152.      * @param   string  $valor      Valor a buscar
  153.      * @return  array
  154.      */
  155.     public function findByColumn($titulo, $valor)
  156.     {
  157.        return $this->_search($this->_excel, $titulo, $valor);
  158.     }
  159.    
  160.     /**
  161.      * Extraida de :
  162.      * @link http://php.net/manual/es/function.array-search.php
  163.      */
  164.     private function _search($array, $key, $value)
  165.     {
  166.         $results = array();
  167.         if (is_array($array)) {
  168.             if (isset($array[$key]) && $array[$key] == $value ) {
  169.                 $results[] = $array;
  170.             }  
  171.             foreach ($array as $subarray) {
  172.                 $results = array_merge($results, $this->_search($subarray, $key, $value));
  173.             }  
  174.         }
  175.         return $results;
  176.     }  
  177.  
  178.     /**
  179.      * Retorna un arreglo con el valor buscado en la columna indicada o no y la cantidad
  180.      * de veces que aparece el valor en las columnas si no se indica la misma.
  181.      * La busqueda es por valor aproximado.
  182.      * @param   string  $buscar     Valor a Buscar
  183.      * @param   string  $calve      Titulo de La columna donde se buscara o nada por Cualquiera.
  184.      * @return  array
  185.      */
  186.     public function findByCount($buscar, $titulo = null)
  187.     {
  188.         return $this->_recursiveArraySearchAll($this->_excel, $buscar, $titulo);
  189.     }
  190.    
  191.     /**
  192.      * Extraida de :
  193.      * @link http://php.net/manual/es/function.array-search.php
  194.      */        
  195.     private function _recursiveArraySearchAll($haystack, $needle, $index = null)
  196.     {
  197.         $arrIterator    = new RecursiveArrayIterator($haystack);
  198.         $recIterator    = new RecursiveIteratorIterator($arrIterator);
  199.         $resultkeys     = array();
  200.                      
  201.         while($recIterator->valid()) {
  202.             if (!is_array($recIterator->current())) {
  203.                 if ((isset($index) AND $recIterator->key() == $index  AND strpos($recIterator->current(), $needle) !== false )
  204.                     OR (!isset($index) AND strpos($recIterator->current(), $needle) !== false)) {
  205.                    
  206.                     $resultkeys[$arrIterator->key()] = isset($resultkeys[$arrIterator->key()])?  $resultkeys[$arrIterator->key()] + 1 : 1;
  207.                 }
  208.             }            
  209.             $recIterator->next();
  210.         }
  211.         arsort($resultkeys);
  212.         return $resultkeys;              
  213.     }    
  214.    
  215.    
  216.     /**
  217.      * Metodo ordenar.
  218.      * Ordena los resultados de acuerdo a la clave elegida.
  219.      * @param   string  $clave  Clave por la cual se quiere ordenar(titulo de columna).
  220.      * @param   boolean $asc    true para ascendente, false para descendente.
  221.      * @return  array
  222.      */
  223.     public function sort($campo = 'name', $asc = true)
  224.     {
  225.         if (empty($this->_excel)) {
  226.             throw new Exception('Primero debe usar la funcion loadExcel');
  227.         }
  228.         $arrSort    = $this->_excel;
  229.  
  230.         $ordenarPor = (in_array($campo, $this->_titulos))? $campo : $this->_id;
  231.         $ascDesc    = ($asc)? SORT_ASC : SORT_DESC;
  232.         $caracter   = 0;
  233.  
  234.         foreach ($arrSort as $ordenado) {
  235.             $tmpArray[] = $ordenado[$ordenarPor];
  236.             $caracter   = is_string($ordenado[$ordenarPor])? $caracter+1 : $caracter;
  237.         }
  238.        
  239.         $numero     = ($caracter)? SORT_STRING : SORT_NUMERIC;
  240.  
  241.         array_multisort($tmpArray, $ascDesc, $numero, $arrSort);
  242.         return $arrSort;
  243.     }
  244.    
  245.     /**
  246.      * Retorna el Valor para una Celda Dada, buscando por el Array.
  247.      * @param   string  $celda  Celda Excel tipo A1
  248.      * @return  mixed   Valor de la Celda
  249.      */
  250.     public function valueCellFromArray($celda)
  251.     {
  252.         $excelOriginal  = array_values($this->_excel);
  253.         list($columna, $fila) = PHPExcel_Cell::coordinateFromString($celda);
  254.         $columna        = PHPExcel_Cell::columnIndexFromString($columna);
  255.        
  256.         if ( ($fila) > $this->_filas || ($columna) > $this->_columnas ) {
  257.             return null;
  258.         }
  259.        
  260.         $retorno    = null;
  261.         if ($fila == 1) {
  262.             $retorno    = $this->_titulos[$columna - 1];
  263.         } else {
  264.             $excelOriginal  = array_values($excelOriginal[$fila - 2]);
  265.             $retorno   = $excelOriginal[$columna - 1];
  266.         }
  267.        return $retorno ;
  268.     }
  269.    
  270.     /**
  271.      * Retorna el Valor de una Celda Especifica, sin tener que realizar la
  272.      * carga del Arreglo.
  273.      * @param   string  $celda  Referencia de Celda tipo A1
  274.      * @return  mixed
  275.      */
  276.     public function getValueCellFromExcel($celda)
  277.     {
  278.         list($columna, $fila) = PHPExcel_Cell::coordinateFromString($celda);
  279.         $columna    = PHPExcel_Cell::columnIndexFromString($columna);
  280.  
  281.         return $this->_createObjWorksheet()->getCellByColumnAndRow($columna - 1, $fila)->getCalculatedValue();
  282.     }
  283. }
Elimine comentarios para que entrara en un post.

Saludos
__________________
"La imaginación es más importante que el conocimiento. El conocimiento es limitado, mientras que la imaginación no" -- A.Einstein
objetivophp.com,twitter.com/objetivophp

Etiquetas: excel, registro
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta

SíEste tema le ha gustado a 1 personas




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