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?
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);
    $i++;
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With