Refactor PHP code that outputs csv with formulas
I have some PHP code that is to create a table with formulas already in it to sum some columns. There seems to be a much more elegant way to do this than the code below. What are some refactorings or design patterns that could improve something like the code below?
<?
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);
?>
0
a source to share
1 answer
Use PEAR :: Spreadsheet_Excel_Writer , it will actually impose some good design principles on you. Moreover, it will sanitize and normalize all inputs.
+2
a source to share