I am attempting to use a ReadFilter with PHPExcel to only read in certain columns.
I am using the example from their documentation:
class columnFilter implements PHPExcel_Reader_IReadFilter
{
private $_startRow = 0;
private $_endRow = 0;
private $_columns = array();
public function __construct($startRow, $endRow, $columns) {
$this->_startRow = $startRow;
$this->_endRow = $endRow;
$this->_columns = $columns;
}
public function readCell($column, $row, $worksheetName = '') {
if ($row >= $this->_startRow && $row <= $this->_endRow) {
if (in_array($column,$this->_columns)) {
return true;
}
}
return false;
}
}
I am using an array called $importColsFilter which is shown below. I am passing this as the column for the ReadFilter.
$importColsFilter
Array (
[0] => A
[1] => B
[2] => C
[3] => H
[4] => I
[5] => J
)
$filterColumns = new columnFilter(2,8,$importColsFilter);
$objReader->setReadFilter($filterColumns);
$sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
When I grab the entire sheet ($sheetData), I was expecting to only get Columns A, B, C, H, I, and J. However, I am getting columns A through J as a range and anything in between that as seen with the array dump below.
$sheetData
Array (
[A] => CellValue1
[B] => CellValue2
[C] => CellValue3
[D] =>
[E] =>
[F] =>
[G] =>
[H] => CellValue4
[I] => CellValue5
[J] => CellValue6
)
The above looks to be the behavior of passing a range array to the filter instead of a normal array like so: new columnFilter(2,8,range('A','J'))
It appears the filter works for grabbing the data, but it's dumping the columns into the array anyway with NULL value. Is this the expected behavior? Can I just return the columns I want?
I was looking for a clean solution using the PHPExcel class. If there is no way there, I can just remove the array entries that are returned as NULL and dump it into another array. An example below:
foreach(array_Keys($sheetData) as $sheetDataKey) {
foreach($sheetData[$sheetDataKey] as $key => $value) {
if(array_key_exists($key, $sheetData[$sheetDataKey]) && is_null($sheetData[$sheetDataKey][$key])) {
unset($sheetData[$sheetDataKey][$key]);
}
}
}
The portion in the class that is checking for the column to be read is in the array passed to the function, that it would only return that column. I wasn't expecting to see columns returned with a NULL value. if (in_array($column,$this->_columns))
Is there anyway to do this with straight PHPExcel, or should I just pop the array entries that are NULL?