18

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?

4

3 回答 3

29

您可以像这样设置数组中的数据:

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

fromArray 适用于二维数组。第一个参数是二维数组,第二个参数是空值时使用什么,最后一个参数是左上角的位置。

否则,您将需要遍历数据:

$worksheet = $objPHPExcel->getActiveSheet();
foreach($sheet as $row => $columns) {
    foreach($columns as $column => $data) {
        $worksheet->setCellValueByColumnAndRow($column, $row + 1, $data);
    }
}
于 2011-04-04T23:22:31.003 回答
22
$rowID = 1;
foreach($sheet as $rowArray) {
   $columnID = 'A';
   foreach($rowArray as $columnValue) {
      $objPHPExcel->getActiveSheet()->setCellValue($columnID.$rowID, $columnValue);
      $columnID++;
   }
   $rowID++;
}

或者

$objPHPExcel->getActiveSheet()->fromArray($sheet);
于 2011-04-04T23:21:02.137 回答
0

据我所知,在使用 PHP excel 填充工作表时,您不需要知道最终 Excel 工作表的高度和宽度。您可以只使用嵌套的 foreach 循环来读取所有嵌套数组并使用适当的变量来构建单元格引用并将它们添加到工作表中。该插件将处理大小。

于 2011-04-04T23:19:51.157 回答