简体   繁体   English

如何从 PhpSpreadsheet 中的合并单元格中读取值

[英]How to read value from merged cells in PhpSpreadsheet

 $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
 $spreadsheet = $reader->load($_FILES['mapping_file']['tmp_name']);
 $sheetData = $spreadsheet->getActiveSheet()->toArray();

This is my code to read excel data from php, using PhpSpreadsheet, the return is array.这是我使用PhpSpreadsheet从php读取excel数据的代码,返回是数组。 But when the cell is merged, it only return single value where the cell is merged, and the other value is null.但是合并单元格时,它只返回合并单元格的单个值,其他值为null。

        // loop to fill empty value from merged cells //
        for($i=0; $i<count($DuplicatedSheetData);$i++){
            // explode merge cells range //
            $CellIndex = explode(":", $DuplicatedSheetData[$i]);

            // get main cell with value, ex N25:N27 , the value only stored in N25 //
            $CellValue = $spreadsheet->getActiveSheet()->getCell($CellIndex[0])->getValue();

            // starting index //
            $StartIndex = (int) substr($CellIndex[0],1,2);

            // ending index // 
            $EndIndex = (int) substr($CellIndex[1],1,2);
            
            // column name example "A" ,"B" //
            $ColumnName = substr($CellIndex[0],0,1);      
            
            // loop to copy the value from main cell, to other cell //
            for($j = $StartIndex;$j <= $EndIndex; $j++){
                $spreadsheet->getActiveSheet()->setCellValue($ColumnName.$j , $CellValue);
            }

        }

        // map to array and remove empty value //
        $sheetData = $spreadsheet->getActiveSheet()->toArray();
        $sheetData = array_values(array_map('array_filter', $sheetData));

Basicly i'm just copying the main value to other cells in range that doesn't have value.基本上我只是将主要值复制到范围内没有值的其他单元格。

I had the same problem, and I find out that that cells were not read but the first (with the value).我有同样的问题,我发现没有读取单元格,而是第一个(有值)。 To solve create a copy of PhpOffice\PhpSpreadsheet\Reader\Xls, and change readMergedCells() to readDefault() for merged cells.要解决此问题,请创建 PhpOffice\PhpSpreadsheet\Reader\Xls 的副本,并将合并单元格的 readMergedCells() 更改为 readDefault()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM