Sorting worksheet data in PHP while keeping formatting

Topics: Developer Forum
Nov 28, 2013 at 11:33 PM
I am modifying a worksheet by updating/adding/removing rows, depending on what action the user takes at the front-end. The worksheet is in alphabetical order and must remain that way after it is updated. The worksheet is also formatted with certain cells highlighted, bolded, etc.

I understand that there isn't a function native to PHPExcel to sort worksheet data so I am using PHP to do so.

I am extracting the data (using toArray), sorting the data (using array_multisort) and then returning the newly sorted data (using fromArray). The worksheet is updated properly with the data in the correct order, however, the formatting remains as-is. For example, if row 3 is highlighted yellow but the content for row 3 moves down 1 row because of an insert higher up - only the data is shifted and not the formatting. I hope that makes sense.

Here is segments of my code:

Read

$dataArray = array();
$dataArray = $objWorksheet->toArray();

Sort

$sortArray = array();
foreach ($dataArray as $key=>$value) {
    $sortArray[$key] = $value[0];
}
array_multisort($sortArray, SORT_ASC, $dataArray);

Write

$objWorksheet->fromArray($dataArray);
Is there a better way to do this - sort a worksheet while preserving the formatting for each row in the worksheet?