我需要你的帮助来解决一个问题。
我试图找到答案,但我找不到答案。 我使用PHPExcel 1.8.0从excel文件中读取数据。我使用ReadFilter读取特定列。
主要PHP代码。
$price = UPLOAD_DIR . $price;
$file_type = PHPExcel_IOFactory::identify($price);
$filter = new ShipperReadFilter();
$filter->getShipperSettings($shipper);
$reader = PHPExcel_IOFactory::createReader($file_type)->setReadDataOnly(true)->setReadFilter($filter)->load($price);
$worksheet = $reader->getActiveSheet();
$col_number = PHPExcel_Cell::columnIndexFromString($worksheet->getHighestDataColumn());
$data = array();
foreach ($worksheet->getRowIterator($filter->getStartRow()) as $row) {
$cellIterator = $row->getCellIterator();
$item = array();
foreach ($cellIterator as $cell) {
// May be PROBLEM is Here?
array_push($item, $cell->getCalculatedValue());
}
array_push($data, $item);
}
var_dump($data);
ReadFilter代码。
class ShipperReadFilter implements PHPExcel_Reader_IReadFilter {
public $valid_columns = array();
public $start_row;
public function setValidColumns ($columns) {
$this->valid_columns = $columns;
}
public function getShipperSettings ($shipper) {
switch ($shipper) {
// Shipper 1
case 1 :
$this->setValidColumns(array('A', 'D', 'F'));
$this->start_row = 4;
break;
// Shipper 2
case 2 :
$this->setValidColumns(array('A', 'R', 'T'));
$this->start_row = 7;
break;
// Shipper 3
case 3 :
$this->setValidColumns(array('H', 'I', 'J'));
$this->start_row = 14;
break;
}
}
public function getStartRow () {
return $this->start_row;
}
public function readCell($column, $row, $worksheetName = '') {
if (in_array($column, $this->valid_columns)) {
return true;
}
return false;
}
}
结果
array(3501) {
[0]=> array(2) {
[0]=> string(11) "01-00018239"
[1]=> float(2493)
}
但我需要这个
array(3501) {
[0]=> array(3) {
[0]=> string(11) "01-00018239"
[1]=> float(2493)
[2]=> null // or '', or 0
}
有没有正确的方法来解决这个问题?谢谢。
答案 0 :(得分:2)
默认情况下,单元迭代器只会迭代实际存在的单元格
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false);
$item = array();
foreach ($cellIterator as $cell) {
array_push($item, $cell->getCalculatedValue());
}
但是,如果您正在为每一行构建一个计算值数组,那么您可能会发现使用工作表的rangeToArray()方法效率更高。
修改强>
仅获取与您的读取过滤器列列表匹配的单元格:
foreach ($cellIterator as $cell) {
$item[$cell->getColumn()] = $cell->getCalculatedValue();
}
$item = array_intersect_key($item, array_flip($filter->valid_columns));
或
foreach ($cellIterator as $cell) {
if(in_array($cell->getColumn(), $filter->valid_columns)) {
array_push($item, $cell->getCalculatedValue());
}
}