Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array to Excel 2007 using PHPExcel

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->setActiveSheetIndex(0);
$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?

like image 718
Njuguna Mureithi Avatar asked Oct 03 '13 09:10

Njuguna Mureithi


3 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');
like image 74
Mark Baker Avatar answered Nov 05 '22 12:11

Mark Baker


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.

like image 45
gregory Avatar answered Nov 05 '22 12:11

gregory


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);
    $i++;
}
like image 1
k102 Avatar answered Nov 05 '22 12:11

k102