简体   繁体   中英

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. But when the cell is merged, it only return single value where the cell is merged, and the other value is 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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