PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, October 5, 2022

[FIXED] How to find correct columns by data from 1st row phpexcel

 October 05, 2022     php, phpexcel     No comments   

Issue

I have excel file with some certain data i need.

"Category" is in first row of excel file.

Thing is that this data can be in different columns.

Is it possible to get column name based on data in first row ?

Example sheet:

enter image description here

For example, i need to get aircraft type and category, wich in this case are columns I & H.

At the moment i do it like this:

$allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
$arrayCount = count($allDataInSheet);
for($i=2;$i<=$arrayCount;$i++){
   $aircraftType = trim($allDataInSheet[$i]["I"]);
   $flightCategory = trim($allDataInSheet[$i]["H"]);

   #insert all data in these columns to database
   $query = "INSERT INTO {$databasetable} (aircraftType, flightCategory) 
      VALUES('$aircarftType', '$flightCategory')";  
   mysql_query($query) or trigger_error(mysql_error()." in ".$query);
}

But how can i do it, when i dont know column letter? Maybe in next file aircraftType is in K and flightCategory is in L...

So is there a way to get column letter based on data in first row.

I think i could propably do it if i save all data to database, and then take it out with some where clauses, but maybe there is better way of doing this directly with PHPExcel ?

I am not really good explaining things, so sorry if this is confusing, please ask and i try to explain more.

Thanks in advance for help.


Solution

A simple call using the worksheet's rangeToArray() will give you an array of the headers

$headers = $objPHPExcel->getActiveSheet()
    ->rangeToArray(
        'A1:'.$objPHPExcel->getActiveSheet()->getHighestColumn().'1',
        null,
        false,
        false,
        true
    );
$headers = $headers[1];

The resultant array has the column letter as the key, and the cell content as the value; and you can then use it to map the appropriate columns to your data



Answered By - Mark Baker
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing