Phpexcel deleting a column or columns

10,054

When you delete a column, such as column A, PHPExcel doesn't simply blank out all the cells in column A, but shuffles all the other columns to fill the gap... so column B becomes the new column A, column C becomes the new column B, etc. This emulates MS Excel's behaviour.

If your array of columns to delete contains A and B: you delete column A first. The previous column B now becomes column A, the previous column C becomes column B, previous column D becomes the new column C. You then delete column B... but the data that you're actually is the data that was previously in column C... not the column that you'd planned to delete... you'd really intended to delete the data from the column that is now column A.

To fix this, you need to delete your columns in the reverse order; so you'd delete column B first, and then column A.

array_reverse($toremove_arr);
$toremove_num = count($toremove_arr);
for($i=0; $i < $toremove_num; $i++){
    $objPHPExcel->getActiveSheet()->removeColumn($toremove_arr[$i], 1);
}
Share:
10,054
Mervyn
Author by

Mervyn

Updated on June 04, 2022

Comments

  • Mervyn
    Mervyn almost 2 years

    I would like to delete a column one at a time without it deleting the right side of the columns. I have gone through the first row and where if its blank I want to delete the column only. But the function only allows me to delete the column and the one next to it. y scenerio Column (M has value) (N has no value) (O has no value) (P has value) (Q has value)

    $toremove_arr=array();
    for ($ga='A'; $ga !== $highestCol; $ga++){
        $col=$objPHPExcel->getActiveSheet()->getCell($ga.'1')->getValue();
        if ($col=='') {
            $toremove_arr[]=$ga;
        }
    }
    $toremove_num  = count($toremove_arr);
    for($i=0; $i < $toremove_num; $i++){
        $objPHPExcel->getActiveSheet()->removeColumn($toremove_arr[$i], 1);
    }