使用 phpExcel 读取文件时删除隐藏行?

Remove hidden rows when reading file with phpExcel?

当使用 toArray 方法使用 phpExcel 读取 sheet 时,隐藏的行也会被解析。

有没有我可以在 toArray 之前使用的方法来删除隐藏行?

到目前为止的代码,使用 Codeigniter

$this->load->library('excel');
$objPHPExcel = PHPExcel_IOFactory::load($upload_data['full_path']);

foreach ($objPHPExcel->getAllSheets() as $sheet) {
    $sheets[$sheet->getTitle()] = $sheet->toArray();
}

$data = array();
foreach ($sheets['Data'] as $key => $row) {
    if ($key > 0) {
        $item = array();
        $item['name'] = $row[1];
        $item['code'] = $row[2];
        $data[] = $item;
    }
}

使用 PHPExcel_Worksheet::toArray 将 sheet 转换为数组时,您将获得所有行,无论它们是否可见。

如果您只想过滤可见行,则必须遍历这些行并检查它们是否可见。您可以使用

检查行的可见性
$sheet->getRowDimension($row_id)->getVisible()

$row_id starts with 1 (and not 0), same is in excel

这是一个如何在您的代码中使用它的示例。我稍微改变了您获取 Data sheet 的方式,因为您不需要遍历 sheet,您可以使用getSheetByName 函数。

$data_sheet = $objPHPExcel->getSheetByName('Data');
$data_array = $data_sheet->toArray();
$data = [];

foreach ($data_sheet->getRowIterator() as $row_id => $row) {
    if ($data_sheet->getRowDimension($row_id)->getVisible()) {
        // I guess you don't need the Headers row, note that now it's row number 1
        if ($row_id > 1) { 
            $item = array();
            $item['name'] = $data_array[$row_id-1][1];
            $item['code'] = $data_array[$row_id-1][2];
            $data[] = $item;
        }
    }
}