Convert Excel column key to array index (for CSVs) [php]
Scenario: CSV file created in Excel, pulled into PHP script with fgetcsv() or equivalent CSV reader. Excel's columns are alphabetical, A-Z, AA-AZ, ... ZZ, AAA, etc. CSV readers (I'm working with php-csv-utils) generate two-dimensional arrays, rows first then columns (reverse of Excel), so A2 is [1][0] (0 being the first).
I needed to pull arbitrary cells out using the Excel keys, so I created the following algorithm. It works on the premise that the Excel columns use a base-26 number system:
I needed to pull arbitrary cells out using the Excel keys, so I created the following algorithm. It works on the premise that the Excel columns use a base-26 number system:
/** * get cell in array by equivalent excel column/row keys * need to convert alphanumeric column to numeric index * (A-Z, AA-AZ, BA-BZ, etc) * also: $data is parsed in reverse order, as $data[$row][$column] * @return cell in $data at $alphaCol/$numRow position */ function getCell($data, $alphaCol, $numRow) { $numCol = 0; $letters = str_split( strtoupper( strrev($alphaCol) ), 1); foreach($letters as $level=>$letter) { // ($level is numeric key) $letterNum = ord($letter) - ord('A') + 1; $numCol += $letterNum * pow(26, $level); } // compensate for indeces starting at 0 $numCol -= 1; $numRow -= 1; if (is_array($data) and isset($data[$numRow][$alphaCol])) { return $data[$numRow][$numCol]; } return null; // not found }