我正在创建一个网页,您必须在其中上传excel文件(csv,xls或xlsx)。 然后我必须检查文件中的列数,因为can必须只包含两列。我已经找到了如何做到这一点,但只针对csv文件:
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);
}
现在,我的问题是:是否可以使用类似的功能,可以为所有3种文件格式执行此操作?
提前致谢
答案 0 :(得分:2)
绝对使用可以读取不同格式的库。正如Mark Baker所指出的那样PHPExcel将是Excel格式的一个很好的选择。
类似的东西:
$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;
}