使用PHPOffice/PhpSpreadsheet包进行excel文件解析时,发现有一列数据解析出错
发现是VLOOKUP函数解析出错,
excel中设置的函数为 VLOOKUP(A5,Sheet2!$A$1:$AG$50,{12,13,12},FALSE)
跟踪代码后发现是在{12,13,12}这一段时出错,
需要修改PhpOffice\PhpSpreadsheet\Calculation\LookupRef\LookupBase.php的函数validateIndexLookup
在函数最前面加入代码
if (is_array($index_number)) {
$index_number = $index_number[0];
}
原代码:
protected static function validateIndexLookup(array $lookup_array, $index_number): int
{
// index_number must be a number greater than or equal to 1.
// Excel results are inconsistent when index is non-numeric.
// VLOOKUP(whatever, whatever, SQRT(-1)) yields NUM error, but
// VLOOKUP(whatever, whatever, cellref) yields REF error
// when cellref is '=SQRT(-1)'. So just try our best here.
// Similar results if string (literal yields VALUE, cellRef REF).
if (!is_numeric($index_number)) {
throw new Exception(ExcelError::throwError($index_number));
}
if ($index_number < 1) {
throw new Exception(ExcelError::VALUE());
}
// index_number must be less than or equal to the number of columns in lookup_array
if (empty($lookup_array)) {
throw new Exception(ExcelError::REF());
}
return (int) $index_number;
}
修改后代码
protected static function validateIndexLookup(array $lookup_array, $index_number): int
{
if (is_array($index_number)) {
$index_number = $index_number[0];
}
// index_number must be a number greater than or equal to 1.
// Excel results are inconsistent when index is non-numeric.
// VLOOKUP(whatever, whatever, SQRT(-1)) yields NUM error, but
// VLOOKUP(whatever, whatever, cellref) yields REF error
// when cellref is '=SQRT(-1)'. So just try our best here.
// Similar results if string (literal yields VALUE, cellRef REF).
if (!is_numeric($index_number)) {
throw new Exception(ExcelError::throwError($index_number));
}
if ($index_number < 1) {
throw new Exception(ExcelError::VALUE());
}
// index_number must be less than or equal to the number of columns in lookup_array
if (empty($lookup_array)) {
throw new Exception(ExcelError::REF());
}
return (int) $index_number;
}