PHP excel - data looping?
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);
Related videos on Youtube
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, 2020Comments
-
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 about 13 years@Mark Baker fixed, and thanks. I really appreciate your work.
-
Aziz almost 12 yearsWhere we've get $rows and $columns in foreach loop above?
-
Aditya M P over 11 yearsYou should probably make a note that 2D arrays work but only in case of regular arrays.
-
Oskar Calvo about 11 yearsGreat answer Jacob, it helps me a lot, and I save a lot of time.
-
Jacob almost 11 years$rows is your 2 dimensional array ($sheets from the question)... I'll update the answer to remove the confusion.