Search code examples
phphtmlexcelfgetcsv

Check number of columns in uploaded excel-file


I'm creating a web page in which you have to upload a excel-file (either csv, xls or xlsx). Then I have to check the number of columns in the file, because the can must only contain TWO columns. I already find how to do this, but only for a csv-file:

if (($file = fopen($path, "r")) !== FALSE){
    while ($line = fgetcsv($file)){
        $numcols = count($line);
        if ($numcols != 2) {
            echo "The number of columns in your file is not correct. The file must contain only 2 columns. ";
            break;
        }
        $col = $line[0]; 
        echo "right! numcols = " . $numcols . "<br>";    
        break;
    }
    fclose($file);
}

Now, my question is: is it possible to use a similar function which can do this for all 3 file-formats?

Thanks in advance


Solution

  • Definitely use a library that can read the different formats. As Mark Baker pointed out PHPExcel would be a good choice for the Excel formats.

    Something like:

    $colCount = checkExcelFile($path)
    
    function checkExcelFile($path){
        $workbook = PHPExcel_IOFactory::load($path);
    
        // $column should then contain the highest column that is being used. 
        // It will be in the form A or B or AA etc. but if you are only expecting 2 columns,
        // then you would be expected 'B', so that would need to be converted to a number
        $column = $workbook->getActiveSheet()->getHighestDataColumn();
        $colNumber = PHPExcel_Cell::columnIndexFromString($column);
    
        return $colNumber;
    }