AccesoDatosExcel.php
2.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
<?php
namespace clases\accesoDatos;
require_once dirname(__FILE__).'/../PHPExcel.php';
use \PHPExcel_Settings;
use \PHPExcel_IOFactory;
use \PHPExcel_CachedObjectStorageFactory;
use \PHPExcel_Worksheet;
/**
* Obtiene datos de un archivo CSV.
*/
class AccesoDatosExcel implements iAccesoDatos {
private $hoja, $iterador;
/**
*
* @param string $archivo
* @param int $posicionActual
* @param int $cantidadProcesable
* @param int $numLineasCabecera
*/
function __construct($archivo, $posicionActual, $cantidadProcesable, $numLineasCabecera = 1) {
$this->hoja = $this->cargarExcel($archivo, $posicionActual + $numLineasCabecera, $cantidadProcesable);
$this->iterador = $this->hoja->getRowIterator();
$this->saltarLineas($posicionActual, $numLineasCabecera);
}
public function obtenerFila() {
$resultado = false;
if($this->iterador->valid()) {
$fila = $this->iterador->current();
$iteradorCelda = $fila->getCellIterator();
$iteradorCelda->setIterateOnlyExistingCells(false);
$resultado = array();
foreach ($iteradorCelda as $celda) {
$resultado[] = $celda->getValue();
}
$this->iterador->next();
}
return $resultado;
}
/**
* Avanza el puntero hasta una linea.
* @param int $posicionActual La linea a procesar.
* @param int $numLineasCabecera
*/
private function saltarLineas($posicionActual, $numLineasCabecera) {
$posicionActual += $numLineasCabecera;
$this->iterador->rewind();
for ($i = 0; $i < $posicionActual; $i++) {
if($this->iterador->valid()) {
$this->iterador->next();
}
else {
break;
}
}
}
/**
* Cierra el fichero.
*/
public function cerrarArchivo() {
if($this->hoja) {
$this->hoja->disconnectCells();
}
}
/**
* Devuelve una hoja activa del archivo indicado.
* @param string $archivo
* @param int $comienzo
* @param int $lineasLeibles
* @return PHPExcel_Worksheet
*/
private function cargarExcel($archivo, $comienzo, $lineasLeibles) {
//Podría ser que esto no fuese compatible con todos los servidores
PHPExcel_Settings::setCacheStorageMethod(PHPExcel_CachedObjectStorageFactory::cache_to_sqlite3);
$inputFileType = PHPExcel_IOFactory::identify($archivo);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$chunkFilter = new ChunkReadFilter();
$objReader->setReadFilter($chunkFilter);
$chunkFilter->setRows($comienzo, $lineasLeibles);
$objPHPExcel = $objReader->load($archivo);
return $objPHPExcel->getActiveSheet();
}
}