Home » Php » php – Array to Excel 2007 using PHPExcel

php – Array to Excel 2007 using PHPExcel

Posted by: admin July 12, 2020 Leave a comment


I have this 2 dimensional array that I want to export as an excel file using PHPExcel.

// create a simple 2-dimensional array
$data = array(
   1 => array ('Name', 'Surname'),
   array('Schwarz', 'Oliver'),
   array('Test', 'Peter')

The problem is that I cannot predict the number of keys in the array so it becomes hard to use this method

$objPHPExcel->getActiveSheet()->SetCellValue('A1', 'Hello');
$objPHPExcel->getActiveSheet()->SetCellValue('B2', 'world!');
$objPHPExcel->getActiveSheet()->SetCellValue('C1', 'Hello');
$objPHPExcel->getActiveSheet()->SetCellValue('D2', 'world!');

I am trying to generate a for loop that will do this, any help?

How to&Answers:

PHPExcel has a built-in method for setting cells from an array in a single step:

$data = array(
    array ('Name', 'Surname'),
    array('Schwarz', 'Oliver'),
    array('Test', 'Peter')
$objPHPExcel->getActiveSheet()->fromArray($data, null, 'A1');


for this I would use the function

$objPHPExcel->getActiveSheet()->SetCellValueByColumnAndRow($column, $row, $text)

and run the foreach on the arrays indexes. Columns start at 0, rows at 1.


this one may help:

$i = 0;
foreach ($data as $key => $value){
    $objPHPExcel->getActiveSheet()->SetCellValue(PHPExcel_Cell::stringFromColumnIndex($i).'1', $key);
    $objPHPExcel->getActiveSheet()->SetCellValue(PHPExcel_Cell::stringFromColumnIndex($i+1).'2', $value);


You can use foreach instead when traversing an array , it will give you key=>value pair.

Please let me know if expect anything different.