PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, October 4, 2022

[FIXED] How detect is cell merged using PhpSpreadsheet

 October 04, 2022     php, phpexcel, spreadsheet     No comments   

Issue

Using PhpSpreadsheet, when I read data from the xls table, I need to find out whether this cell is merged with others, if yes, then do certain actions with it, if not, then do nothing

at the moment I thought of only checking for the presence of empty array elements after the text cell, but this solution is not quite universal ...

...
$inputFileName = $_FILES['uploadfile']["tmp_name"];
echo 'TMP-FILE-NAME: ' . $inputFileName;

$spreadsheet = IOFactory::load($inputFileName); //create new speedsheen object
$loadedSheetNames = $spreadsheet->getSheetNames(); //get name of Sheet

//and than print it
    //get Sheet Name
foreach ($loadedSheetNames as $sheetIndex => $loadedSheetName) {

  $sheet = $spreadsheet->getSheet($sheetIndex);
  echo "<table border=\"1\">";
  $rows = $sheet->toArray();
   **$mergeCell = $sheet->getMergeCells(); // - This is the answer to my question**
foreach ($rows AS $row) {
echo "<tr>";
    foreach ($row AS $cell) {
        echo "<td>" . $cell . "</td>";
    }

    }
     echo '<br/>';
}
 echo "</table>";

Solution

In order to check the cell was merged or not

  1. First, you can use getMergeCells function to get all merged cells.

  2. Then do loop in that cells list to check your cell is in or is not in that list.

Summarize: You can use this function to check cell merged or not

// Check cell is merged or not
function checkMergedCell($sheet, $cell){
    foreach ($sheet->getMergeCells() as $cells) {
        if ($cell->isInRange($cells)) {
            // Cell is merged!
            return true;
        }
    }
    return false;
}

The code was referenced from this answer

For PhpSpreadSheet:

  • getMergeCells: https://phpoffice.github.io/PhpSpreadsheet/1.2.0/PhpOffice/PhpSpreadsheet/Worksheet/Worksheet.html#method_getMergeCells
  • isInRange: https://phpoffice.github.io/PhpSpreadsheet/1.2.0/PhpOffice/PhpSpreadsheet/Cell/Cell.html#method_isInRange


Answered By - Ngoc Nam
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing