views:

104

answers:

1

I have some PHP code that is designed to make a spreadsheet with formulas already in it to sum some columns. It seems there should be a much more elegant way to do this than the code below. What are some refactorings or design patterns that could accomplish something like the code below better?

<?
echo ",Current Milestone,Total Hours,Milestone 1 Hours,Milestone 2 Hours,Milestone 3 Hours\n";
$row = 2; 
$totSSRange = ""; 
foreach($departments as $dept){
 $deptStartRow = $row + 1;
 echo $dept['name']."\n";
 foreach($dept['modules'] as $module){
  $row++;
  echo $module['name'].','.$module['ms'].',=SUM(D'.$row.':F'.$row.'),'.$module['m1'].','.$module['m2'].','.$module['m3']."\n";
 }
 $deptSSRange = "C".$deptStartRow.":C".$row; 
 $totSSRange .= $deptSSRange.","; 
 $sumStr = "=SUM(".$deptSSRange.")"; 
 echo 'Sum,,'.$sumStr.','.str_replace("C","D",$sumStr).','.str_replace("C","E",$sumStr).','.str_replace("C","F",$sumStr)."\n\n";
 $row+=3; 
} 
$totSumStr = "\"=SUM(".$totSSRange.")\"";
echo 'Total,,'.$totSumStr.','.str_replace("C","D",$totSumStr).','.str_replace("C","E",$totSumStr).','.str_replace("C","F",$totSumStr);
?>
+2  A: 

Use PEAR::Spreadsheet_Excel_Writer, it will actually enforce some good design prenciples on you, plus it will sanitize and normalize all the input.

duckyflip