Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP excel - data looping?

I have an array of arrays of data.

so the basic format is

$sheet = array(
  array(
    'a1 data',
    'b1 data',
    'c1 data',
    'd1 data',
  ),
  array(
    'a2 data',
    'b2 data',
    'c2 data',
    'd2 data',
  ),
  array(
    'a3 data',
    'b3 data',
    'c3 data',
    'd3 data',
  )
);

When I am passed the array I have no idea how many columns or rows there will be. What I want to do is using php excel create an excel sheet out of the array.

from what I have seen, the only way to set data is to use $objPHPExcel->getActiveSheet()->setCellValue('A1', $value);

So my question is

How would you loop over the cells?

remembering that there could be say 30 columns and say 70 rows which would be AD70 So, how do you loop that?

Or is there a built in function to turn an array to a sheet?

like image 484
Hailwood Avatar asked Apr 04 '11 23:04

Hailwood


2 Answers

You can set the data from an array like so:

$objPHPExcel->getActiveSheet()->fromArray($sheet, null, 'A1');

fromArray works with 2D arrays. Where the 1st argument is the 2D array, the second argument is what to use if there is a null value, and the last argument is where the top left corner should be.

Otherwise you would need to loop through the data:

$worksheet = $objPHPExcel->getActiveSheet();
foreach($sheet as $row => $columns) {
    foreach($columns as $column => $data) {
        $worksheet->setCellValueByColumnAndRow($column, $row + 1, $data);
    }
}
like image 143
Jacob Avatar answered Nov 14 '22 17:11

Jacob


$rowID = 1;
foreach($sheet as $rowArray) {
   $columnID = 'A';
   foreach($rowArray as $columnValue) {
      $objPHPExcel->getActiveSheet()->setCellValue($columnID.$rowID, $columnValue);
      $columnID++;
   }
   $rowID++;
}

or

$objPHPExcel->getActiveSheet()->fromArray($sheet);
like image 22
Mark Baker Avatar answered Nov 14 '22 15:11

Mark Baker