Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPExcel: Set Column Names fromArray using PHP array

Tags:

php

phpexcel

I'm using PHPExcel library to export data to excel. I'm able to get all the data to excel as expected. But how can I set the column names from 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 lines above to set Cell values in first row based on array data as column names. i.e Name, ID, Date,.....

//Add Data

$objPHPExcel->getActiveSheet()->fromArray($data,NULL,'A2');
like image 756
Mr.Kiran Avatar asked Dec 19 '22 18:12

Mr.Kiran


1 Answers

// Header
$objPHPExcel->getActiveSheet()->fromArray(array_keys(current($data)), null, 'A1');
// Data
$objPHPExcel->getActiveSheet()->fromArray($data, null, 'A2');
like image 96
Blob Avatar answered Dec 30 '22 07:12

Blob