phpexcel - 如何从循环fromarray中获取结果集中的所有值

时间:2014-08-23 09:36:20

标签: mysql phpexcel phpactiverecord

我无法弄清楚如何从mysql结果集中获取所有数据(行和列)。 使用此代码,我得到的不是我查询中的所有行:

$row=1; 
$column = 'A';

$sql = "SELECT distinct c.code, p.gestion";
for ($i = 1; $i <= count($steps); $i++) {
    $sql .= "
        ,(SELECT IFNULL(ROUND(SUM(c".$i.".`delta`),1),'')
            FROM charge c".$i.", totalgestion p".$i."
            WHERE c".$i.".code = p.code
            AND c".$i.".steps = ".$i."
            AND c".$i.".actif = 1) as delta".$i.",'' as comments".$i.",
         (SELECT IFNULL(ROUND(SUM(c".$i.".`values`),1),'')
            FROM charges c".$i.", totalgestion p".$i."
            WHERE c".$i.".code = p".$i.".code
            AND c".$i.".year = ".$year."
            AND c".$i.".steps = ".$i." "
            AND c".$i.".actif = 1) as total".$i." ";
    ;
}
$sql .= "
FROM charges c, totalgestion p
WHERE c.code = p.code
AND c.annee = ".$year."
AND c.type = 1
";

$totalvalues = RefTable::find_by_sql($sql);

    foreach ($totalvalues as $totalvalue) {
        $Code = $totalvalue->code;
        $Gestion = $totalvalue->gestion;

        for ($i = 1; $i <= count($etapes); $i++){
            $Del = 'delta'.$i;
            $Com = 'comments'.$i;
            $Tot = 'total'.$i;
            $Delta = $totalvalue->$Del;
            $Comments = $totalvalue->$Com;
            $Total = $totalvalue->$Tot;
    }   
    $datas=array($Code,$Gestion,$Delta,$Comment,$Montant);

    $objPHPExcel->getActiveSheet()->fromArray($datas, null, $column . $row);
         $objPHPExcel->getActiveSheet()->getStyle($column . $row)->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
         $objPHPExcel->getActiveSheet()->getStyle($column . $row)->getFill()->getStartColor()->setRGB('3F6E89');
         $objPHPExcel->getActiveSheet()->getStyle($column . $row)->getFont()->getColor()->setRGB('FFFFFF');
         $row++;
    }

我只得到5列,但必须有8列,因为我已经为最后3列做了一个for循环...: 见图:

enter image description here

..而且我必须得到

如图所示:

enter image description here

在我的例子中,它可以是5列,但也可以是8或11列,因为有关联。 我认为我的for循环在任何地方都不正确 那么如何从循环结果集中获取所有值?

有人有想法吗?

提前致谢

1 个答案:

答案 0 :(得分:1)

您可以关联更多setCellValue

$column_init = 67; // equals C in ascii
$columns = [];
for ($i = 0; $i < count($steps) * 3; $i++) {
    $columns[] = $column_init + $i;
}

$values = [];

foreach ($totalvalues as $totalvalue) {
    $totalvalue = (array)$totalvalue;

    for ($j = 0; $j < count($steps); $j++) {
        $values[] = $totalvalue['delta' . $j];
        $values[] = $totalvalue['comments' . $j];
        $values[] = $totalvalue['total' . $j];
    }

    for ($i = 0; $i < count($columns); $i++) {
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[chr($i)] . $row, $values[$i]);
    }

    $row++;
}