Steve
Steve

Reputation: 2588

How to create a dynamic loop for Excel creation in PHPExcel through PHP

I have a simple PHP DB Query which generates simple 2 column records. All I have to do is to pass them to PHPExcel sheet object.

This is my PHPExcel code:

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

which creates a perfect Pie Chart.

Now I have a simple query whose data I need to pass into this Excel. It's as follows:-

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

My question is how can I pass this format of data through my loop dynamically into PHPExcel code.

Print_r results for $resultstr_pages_visited are :-

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

Upvotes: 0

Views: 2106

Answers (1)

Mark Baker
Mark Baker

Reputation: 212402

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

Upvotes: 3

Related Questions