如何通过PHP在PHPExcel中创建Excel创建的动态循环

时间:2014-06-12 20:56:35

标签: php phpexcel

我有一个简单的PHP DB Query,它可以生成简单的2列记录。我所要做的就是将它们传递给PHPExcel工作表对象。

这是我的PHPExcel代码:

$objPHPExcel = new PHPExcel();
$objWorksheet = $objPHPExcel->getActiveSheet();


$objWorksheet->fromArray(
    array(
        array('My Page Report 1', 14),
        array('My Page Report 2', 12),
        array('My Page Report 3', 7),
        array('My Page Report 4', 5),
        array('My Page Report 5', 4),
        array('My Page Report 6', 2),
        array('My Page Report 7 ', 1),
        array('My Page Report 8', 1),
        array('My Page Report 9', 1)
    )
);

创建一个完美的饼图。

现在我有一个简单的查询,我需要将数据传递到此Excel中。它如下: -

$result = db_query("
    SELECT
      n.title, n.nid,
      COUNT(*) AS times
    FROM
      {node_view_count} a, {node} n where a.nid = n.nid AND a.uid = :uid
    GROUP BY
      n.title
    ORDER BY
      times desc",
    array(':uid'=>$_GET['uid'])) -> fetchAll();



    foreach($result as $r) {    
        $resultstr_pages_visited[] = $r->title.", ".$r->times;
     }


// This creates exactly this kind of line
// 'My Page Report 9', 1 and puts a comma to the end.
implode("," , $resultstr_pages_visited);

我的问题是如何通过我的循环将这种格式的数据动态传递到PHPExcel代码中。

$ resultstr_pages_visited的print_r结果为: -

Array ( [0] => 
    Array 
    ( [0] => My Page Report 1 , 14 ) 
        [1] => Array ( [0] => My Page Report 2, 12 ) 
        [2] => Array ( [0] => My Page Report 3, 7 ) 
        [3] => Array ( [0] => My Page Report 4, 5 ) 
        [4] => Array ( [0] => My Page Report 5, 4 ) 
        [5] => Array ( [0] => My Page Report 6, 2 ) 
        [6] => Array ( [0] => My Page Report 7 , 1 ) 
        [7] => Array ( [0] => My Page Report 8, 1 ) 
        [8] => Array ( [0] => My Page Report 9, 1 ) 
    )

1 个答案:

答案 0 :(得分:3)

$row = 1;
foreach($result as $r) {
    $objWorksheet->fromArray(array($r->title, $r->times), null, 'A'.$row);
    $row++;
}