我目前有以下代码将循环遍历excel文件并返回缺少数据的行。输出如下:
- Row number: 37
- Missing : in cell B37
- Missing : in cell D37
我想要返回的内容如下
- Row number: 37
- Missing nameFirst : in cell B37
- Missing nameLast : in cell D37
其中nameFirst是单元格B1的值,nameLast是D1的值。
<?PHP
require_once 'Excel/PHPExcel.php';
require_once 'Excel/PHPExcel/Reader/Excel2007.php';
class MyReadFilter implements PHPExcel_Reader_IReadFilter
{
public function readCell($column, $row, $worksheetName = '') {
$Retour=false;
$column=PHPExcel_Cell::columnIndexFromString($column);// Warning ! A=1, not zero as usual
if($row<1 || $column>4)
$Retour=false;
else
$Retour=true;
return $Retour;
}
}
echo '<pre>';
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objReader->setReadDataOnly(true);
$objReader->setReadFilter( new MyReadFilter() );
$objPHPExcel = $objReader->load('test.xlsx');
$worksheet=$objPHPExcel->getSheet(0);
foreach ($worksheet->getRowIterator() as $row) {
if($row->getRowIndex()>1){
echo ' - Row number: ' . $row->getRowIndex() . "\r\n";
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false); // Loop all cells, even if it is not set
foreach ($cellIterator as $cell) {
$colIndex = PHPExcel_Cell::columnIndexFromString($cell->getColumn());
if($cell->getCalculatedValue() == "")
echo ' - Missing <THIS IS WHERE I WANT THE INDEX CELL FOR THE COLUMN> :' . 'in cell ' . $cell->getCoordinate() . "\r\n";
}
}
}
echo '</pre>';
?>
我尝试更改回声以包含变量$ colIndex以及:
echo ' - Missing '. $worksheet->getCellByColumnAndRow($colIndex, 1)->getValue(). '. :' . $cell->getCoordinate() . "\r\n";
但这导致返回一行,只返回一个正确的单元格和一大堆空白变量
- Row number: 2
- Missing nameFirst. :B1
- Missing . :E1
- Missing . :F1
- Missing . :G1
- Missing . :H1
答案 0 :(得分:2)
因此,您需要获取当前单元格($ cell)列中第1行的单元格值
echo ' - Missing ' .
$worksheet->getCell($cell->getColumn(). '1')->getValue() .
' :' . 'in cell ' .
$cell->getCoordinate() . "\r\n";
应该能够很好地运作