Ver Mensaje Individual
  #7 (permalink)  
Antiguo 20/10/2012, 18:13
Avatar de portalmana
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