重构使用公式输出csv的PHP代码

时间:2009-05-18 20:55:39

标签: php excel design-patterns csv

我有一些PHP代码,旨在制作一个已包含公式的电子表格来汇总一些列。似乎应该有一个比下面的代码更优雅的方式来做到这一点。有哪些重构或设计模式可以更好地完成下面的代码?

<?
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);
?>

1 个答案:

答案 0 :(得分:2)

使用PEAR::Spreadsheet_Excel_Writer,它实际上会对您强制执行一些好的设计原则。此外,它将消毒并标准化所有输入。