Skip to content

Instantly share code, notes, and snippets.

Created May 13, 2014 14:17
public function removeDuplicates($objPHPExcel) {
//Elements that vary, they have all match to be considered as a duplicate
$worksheet = $objPHPExcel->getActiveSheet();
$urn = array();
$urn2 = array();
$urn3 = array();
$urn4 = array();
foreach ($worksheet->getRowIterator() as $row) {
$rowIndex = $row->getRowIndex();
$cellValue = $worksheet->getCell('A' . $rowIndex)->getValue();
$cellValue2 = $worksheet->getCell('B' . $rowIndex)->getValue();
$cellValue3 = $worksheet->getCell('G' . $rowIndex)->getValue();
$cellValue4 = $worksheet->getCell('H' . $rowIndex)->getValue();
array_push($urn, $cellValue); //Project
array_push($urn2, $cellValue2); //Line
array_push($urn3, $cellValue3); //Name
array_push($urn4, $cellValue4); //ID
}
//If it matches mark with a 1 (has duplicates)
$numberOfURNs = count($urn);
for ($rowIndex = $numberOfURNs; $rowIndex != 1; $rowIndex--) {
$cellValue = $worksheet->getCell('A' . $rowIndex)->getValue();
$cellValue2 = $worksheet->getCell('B' . $rowIndex)->getValue();
$cellValue3 = $worksheet->getCell('G' . $rowIndex)->getValue();
$cellValue4 = $worksheet->getCell('H' . $rowIndex)->getValue();
for ($i = $rowIndex - 2; $i!= 0; $i--) {
if ($urn[$i] == $cellValue) {
if ($urn2[$i] == $cellValue2) {
if ($urn3[$i] == $cellValue3) {
if ($urn4[$i] == $cellValue4) {
//$worksheet->removeRow($rowIndex);
//break;
$objPHPExcel->getActiveSheet()->setCellValue('X' . $rowIndex . '', 1);
}
}
}
}
}
}
//Delete the items that don't have the 1 on the X column ' [not duplicates]
for ($rowIndex = $numberOfURNs; $rowIndex != 1; $rowIndex--) {
$cellValue = $worksheet->getCell('X' . $rowIndex)->getValue();
for ($i = $rowIndex - 1; $i!= 0; $i--) {
if ('1' != $cellValue) {
//$objPHPExcel->getActiveSheet()->setCellValue('' . $rowIndex . '', 1);
$worksheet->removeRow($rowIndex);
break;
}
}
}
//Delete duplicates for the ones marked as 1 [duplicates, leaving only one of each]
for ($rowIndex = $numberOfURNs; $rowIndex != 1; $rowIndex--) {
$cellValue = $worksheet->getCell('A' . $rowIndex)->getValue();
$cellValue2 = $worksheet->getCell('B' . $rowIndex)->getValue();
$cellValue3 = $worksheet->getCell('G' . $rowIndex)->getValue();
$cellValue4 = $worksheet->getCell('H' . $rowIndex)->getValue();
for ($i = $rowIndex - 2; $i != 0; $i--) {
if ($urn[$i] == $cellValue) {
if ($urn2[$i] == $cellValue2) {
if ($urn3[$i] == $cellValue3) {
if ($urn4[$i] == $cellValue4) {
$worksheet->removeRow($rowIndex);
break;
}
}
}
}
}
}
return $objPHPExcel;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment