PHP excel - data looping?

32,638

Solution 1

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

Solution 2

$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);
Share:
32,638

Related videos on Youtube

Hailwood
Author by

Hailwood

I could tell you all about me... but I'd prefer to let my work do the talking for me!

Updated on April 30, 2020

Comments

  • Hailwood
    Hailwood almost 4 years

    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?

  • Jacob
    Jacob about 13 years
    @Mark Baker fixed, and thanks. I really appreciate your work.
  • Aziz
    Aziz almost 12 years
    Where we've get $rows and $columns in foreach loop above?
  • Aditya M P
    Aditya M P over 11 years
    You should probably make a note that 2D arrays work but only in case of regular arrays.
  • Oskar Calvo
    Oskar Calvo about 11 years
    Great answer Jacob, it helps me a lot, and I save a lot of time.
  • Jacob
    Jacob almost 11 years
    $rows is your 2 dimensional array ($sheets from the question)... I'll update the answer to remove the confusion.

Related