PHP excel - 数据循环?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5545406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP excel - data looping?
提问by Hailwood
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.
当我通过数组时,我不知道会有多少列或行。我想要做的是使用 php excel 从数组中创建一个 excel 表。
from what I have seen, the only way to set data is to use
$objPHPExcel->getActiveSheet()->setCellValue('A1', $value);
从我所看到的,设置数据的唯一方法是使用
$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?
记住可能有 30 列和 70 行,这将是AD70
那么,你如何循环?
Or is there a built in function to turn an array to a sheet?
或者是否有内置函数将数组转换为工作表?
回答by Jacob
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.
fromArray 适用于二维数组。第一个参数是二维数组,第二个参数是如果有空值要使用什么,最后一个参数是左上角应该在哪里。
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);
}
}
回答by Mark Baker
$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);
回答by Rasika
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.
据我所知,在使用 PHP excel 填充工作表时,您不需要知道最终 Excel 工作表的高度和宽度。您可以只使用嵌套的 foreach 循环来读取所有嵌套的数组并使用适当的变量来构建单元格引用并将它们添加到工作表中。该插件将处理大小。