简体   繁体   中英

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

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:

在此处输入图片说明

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM