PHPExcel: set column names from an array using PHP array

I am using the PHPExcel library to export data to excel. I can get all the data to succeed as expected. But how to set column names from a PHP array. Here is the code I'm using. Please, help

    $data=(
    array(10) (
      [0] => array(8) (
        [#] => (string)
        [Name] => (string) Student1
        [ID] => (string) 123456
        [Date] => (string) 2016-02-01
        [Group] => (string) Physics
        [Month] => (string) February
        [Year] => (string) 2016
      )
      [1] => array(8) (
        [#] => (string)
        [Name] => (string) Student2
        [ID] => (string) 569874
        [Date] => (string) 2016-02-01
        [Group] => (string) Biology
        [Month] => (string) February
        [Year] => (string) 2016......);

    $objPHPExcel = new PHPExcel();

    $objPHPExcel->setActiveSheetIndex(0);
    $objPHPExcel->getActiveSheet()->setCellValue('A1', "#");
    $objPHPExcel->getActiveSheet()->setCellValue('B1', "Name");
    $objPHPExcel->getActiveSheet()->setCellValue('C1', "ID");
    $objPHPExcel->getActiveSheet()->setCellValue('D1', "Date");
    $objPHPExcel->getActiveSheet()->setCellValue('E1', "Group");
    $objPHPExcel->getActiveSheet()->setCellValue('F1', "Month");
    $objPHPExcel->getActiveSheet()->setCellValue('G1', "Year");

// How to replace / make dynamic rows above to set cell values ​​in the first row based on array data in the form of column names. ie Name, identifier, date, .....

//Add Data

$objPHPExcel->getActiveSheet()->fromArray($data,NULL,'A2');
+4
source share
3 answers

like this?

$objPHPExcel->getActiveSheet()->fromArray(array_keys($data[0]),NULL,'A2');

Now that I know what you want to do, a short explanation.

Array_keys copies all the keys from the array as a value into a numbered array, so if you have such an array:

[#] => (string)
[Name] => (string) Student1
[ID] => (string) 123456
[Date] => (string) 2016-02-01
[Group] => (string) Physics
[Month] => (string) February
[Year] => (string) 2016

It will return after the array:

[0] = "#"
[1] = "Name"
[2] = "ID"
...
+3
// Header
$objPHPExcel->getActiveSheet()->fromArray(array_keys(current($data)), null, 'A1');
// Data
$objPHPExcel->getActiveSheet()->fromArray($data, null, 'A2');
+4

class excelExport {
 public $columns = array(            
        0 => array('id' => "name", 'name' => 'Name'), 
        1 => array('id' => "tlf", 'name' => 'Telephone'),                                   
    );


 public function export(){      


    /** PHPExcel */
    $objPHPExcel = new PHPExcel();

    $objPHPExcel->setActiveSheetIndex(0);
    $objWorkSheet = $objPHPExcel->getActiveSheet();   

        $row =  1;
        $col = 0;
        for ($column = 'A'; ord($column) != ord('A')+count($this->columns); $column++) {

            $cell = $objWorkSheet->getCell($column.$row);
            $cell->setValue($this->columns[$col]["name"]);
            $col++;
        }

        ...
0