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 dat开发者_JS百科a',
'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?
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);
}
}
$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);
As far as I know, you don't need to know the height and width of the final Excel worksheet when populating a worksheet using PHP excel. You can just use a nested foreach loop to read all the nested arrays and use appropriate variables to build up the cell references and add them to the worksheet. The plugin will handle the size.
精彩评论