How detect is cell merged using PhpSpreadsheet - php

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>";

In order to check the cell was merged or not
First, you can use getMergeCells function to get all merged cells.
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

Related

PhpSpreadsheet - Get raw string value for d/m/Y dates instead of being converted to floats

I am trying to read an excel file that has 03/05/2008 kind of format, but when I read using PhpSpreadsheet, it returns me 2008.0.
Is there a way to get the raw string format of columns instead of converting to float?
try {
$inputFileType = IOFactory::identify($path);
try {
$reader = IOFactory::createReader($inputFileType);
$reader->setReadDataOnly(true);
$valuesSpreadsheet = $reader->load($path);
try {
$spreadsheetArr = $valuesSpreadsheet->getActiveSheet()->toArray();
dd($spreadsheetArr);
}
}
}
Edit: I don't want to get a specific cell and convert it to timestamp like the comments below. I want to get as array ->toArray() but getting all raw string formats.
Take out the $reader->setReadDataOnly(true) line prior to loading the data and the values should be displayed properly. If not you can also try the following code.
$path = 'yourPath';
try {
$inputFileType = \PhpOffice\PhpSpreadsheet\IOFactory::identify($path);
try {
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
$valuesSpreadsheet = $reader->load($path);
try {
$spreadsheetArr = $valuesSpreadsheet->getActiveSheet()->toArray(null, null, true, true);
print '<pre>' . print_r($spreadsheetArr, 1) . '</pre>';
} catch (Exception $e) {
echo $e . PHP_EOL;
}
} catch (Exception $e) {
echo 'Unable to load file ' . $path . PHP_EOL;
echo $e . PHP_EOL;
}
} catch (Exception $e) {
echo 'Unable to locate file ' . $path . PHP_EOL;
echo $e . PHP_EOL;
}
toArray() has a parameter to return the cell values formatted as they are in the spreadsheet. Try calling it like this:
$spreadsheetArr = $valuesSpreadsheet->getActiveSheet()->toArray(null, true, true, true);
About 80% of the way down this page is documentation for the toArray() function.
In short, toArray() can accept 4 parameters:
whatever value you want empty cells to return
(boolean) do formulas need to be calculated?
(boolean) does cell formatting matter?
(boolean) do you want the array indexed by the spreadsheet's column and row?
You should use getRowIterator() and getCellIterator() functions to loop through all cells. In the code below, all cells will be returned as raw values.
try {
$inputFileType = IOFactory::identify($path);
try {
$reader = IOFactory::createReader($inputFileType);
$reader->setReadDataOnly(true);
$spreadsheet = $reader->load($path);
$worksheet = $spreadsheet->getActiveSheet();\
foreach ($worksheet->getRowIterator() as $index => $row) {
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(FALSE); //This loops through all cells
$cells = [];
foreach ($cellIterator as $cell) {
$cells[] = $cell->getValue();
}
$rows[] = $cells;
print_r($rows);
}
}
}

How to convert cell object to an array

[
$objWorksheet = $objPHPExcel->getActiveSheet();
foreach ($objWorksheet->getRowIterator() as $row) {
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false);
foreach ($cellIterator as $cell) {
if($cell->getRow()==1||$cell->getColumn()=='A'){
continue;
}
else{
$cell->$_column;
}
}
}][1]
Problem :
I need to get the values of $cell so that I can put it in a MySQL database , if there a good reference to get the methods of cell object?
There are libraries that make the cells of a xls file into an array and then manipulate and to store in a database to automate processes.
phpexcelreader
example of this would
<?php
require_once 'reader.php';
$data = new Spreadsheet_Excel_Reader();
$data->read('archivoxls');
$celdas = $data->sheets[0]['cells']; // obtains cells of file xls
foreach ($celdas as $val) { // print cells
print_r($val);
echo "<br/>";
}

Remove hidden rows when reading file with phpExcel?

When reading a sheet with phpExcel using the toArray method, hidden rows are also parsed.
Is there a method I can use before toArray to remove hidden rows?
Code so far, using 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;
}
}
When converting the sheet to Array using PHPExcel_Worksheet::toArray you will get all of the rows, regardless if they are visible or not.
If you want to filter only the visible rows you will have to iterate over the rows and check for each of them if they are visible or not. You can check the visibility of a row using
$sheet->getRowDimension($row_id)->getVisible()
$row_id starts with 1 (and not 0), same is in excel
Here is an example of how to use it in your code. I changed a bit the way you get the Data sheet, since you don't need to iterate over the sheets, you can just get that specific sheet using the getSheetByName function.
$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;
}
}
}

How to retrieve data from excel file using symfony2 excelbundle?

For a school project, I have to collect data from an Excel file uploaded by the user. I am using Symfony2 and have installed a bundle I found on knpbundles, named ExcelBundle. I read that to collect data with it from an Excel file, I should use the createWriter method of my phpExcel object. That is what I have done as shown below.
public function addContactsFromExcelAction(Request $request) {
$uploadDir = '/var/www'.$request->getBasePath().'/uploads/';
//die(var_dump($uploadDir));
$file = $request->files->get('fichierExcel');
$fileName = $file->getClientOriginalName();
$fileSaved = $file->move($uploadDir,$fileName);
$phpExcelObject = $this->get('phpexcel')->createPHPExcelObject($uploadDir.$fileName);
$writer = $this->get('phpexcel')->createWriter($phpExcelObject, 'Excel2007');
}
But the thing is that actually, I do not really know how to use the writer to collect data from the cells of my excel datasheets.
Please, could anyone give me the trick to achieve my goal ?
You can iterate as this Example:
public function xlsAction()
{
$filenames = "your-file-name";
$phpExcelObject = $this->get('phpexcel')->createPHPExcelObject($filenames);
foreach ($phpExcelObject ->getWorksheetIterator() as $worksheet) {
echo 'Worksheet - ' , $worksheet->getTitle();
foreach ($worksheet->getRowIterator() as $row) {
echo ' Row number - ' , $row->getRowIndex();
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false); // Loop all cells, even if it is not set
foreach ($cellIterator as $cell) {
if (!is_null($cell)) {
echo ' Cell - ' , $cell->getCoordinate() , ' - ' , $cell->getCalculatedValue();
}
}
}
}
}
More samples here

Getting cells by coordinate

foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
foreach ($worksheet->getRowIterator() as $row) {
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false);
// I wish
echo $cellIterator->getCell("A3"); // row: $row, cell: A3
}
}
I'm looking for a similar method which named getCell above or well-writed PHPExcel documentation.
Thanks.
If you have the $row information from RowIterator, you can just easily call:
$rowIndex = $row->getRowIndex ();
$cell = $sheet->getCell('A' . $rowIndex);
echo $cell->getCalculatedValue();
The complete code would be:
foreach($worksheet->getRowIterator() as $row){
$rowIndex = $row->getRowIndex();
$cell = $worksheet->getCell('A' . $rowIndex);
echo $cell->getCalculatedValue();
$cell = $worksheet->getCell('B' . $rowIndex);
echo $cell->getCalculatedValue();
}
This is what I needed:
function coordinates($x,$y){
return PHPExcel_Cell::stringFromColumnIndex($x).$y;
}
implementation:
coordinates(5,7); //returns "E7"
Though one could also do this for A-Z columns:
function toNumber($dest)
{
if ($dest)
return ord(strtolower($dest)) - 96;
else
return 0;
}
function lCoordinates($x,$y){
$x = $toNumber($x);
return PHPExcel_Cell::stringFromColumnIndex($x).$y;
}
implementation:
lCoordinates('E',7); //returns "E7"
Rather than iterate all the Cells in a row, when not use the rangeToArray() method for the row, and then use array_intersect_key() method to filter only the columns that you want:
$worksheet = $objPHPExcel->getActiveSheet();
$highestColumn = $worksheet->getHighestColumn();
$columns = array_flip(array('A','C','E'));
foreach($worksheet->getRowIterator() as $row)
{
$range = 'A'.$row->getRowIndex().':'.$highestColumn.$row->getRowIndex();
$rowData = $worksheet->rangeToArray( $range,
NULL,
TRUE,
TRUE,
TRUE);
$rowData = array_intersect_key($rowData[$row->getRowIndex()],$columns);
// do what you want with the row data
}
EDIT
The latest SVN code introduces a number of new methods to th iterators, including the ability to work with ranges, or set the pointer to specific rows and columns

Categories