Just get one row from PHPExcel - php

I tried to find a way to just get a row using PHPExcel. After numerous searches on the internet, I only found a way to iterate over them, with an optional start row. This lead to the following solution:
foreach ($this->objPHPExcel->getActiveSheet()->getRowIterator($rownumber) as $row) {
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false);
foreach ($cellIterator as $cell) {
echo $cell->getValue();
}
break;
}
but this feels a little ugly. Is there another way to do it?

Yes!
$row = $this->objPHPExcel->getActiveSheet()->getRowIterator($rownumber)->current();
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false);
foreach ($cellIterator as $cell) {
echo $cell->getValue();
}
I don't remember if you are supposed to use next or current. If you are getting the wrong row, use current() instead of next().

$myRow = 123;
$this->objPHPExcel->getActiveSheet()
->rangeToArray(
'A' . $myRow .
':' .
$this->objPHPExcel->getActiveSheet()->getHighestColumn() . $myRow
);
will return the specified row as an array of cells

Related

How detect is cell merged using PhpSpreadsheet

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

Compare a string value in excel using PHPExcel parser

I am trying to parse an excel spreadsheet using phpexcel library in php but I can't get the logic correct for comparing a value in the cell.
I am using following code to read values in excel:
$sheet->getCellByColumnAndRow("10", $row)->getValue()
The HTML output is
☑
And when I try to find all the rows with this value using the following logic I never get the equation true.
for ($row = 5; $row <= $highestRow; ++$row) {
if ($sheet->getCellByColumnAndRow("10", $row)->getValue() == '☑') {
echo 'rowno ' . $row . ' ' . 'BOOKED';
echo '<br/>';
}else{
echo strtolower($sheet->getCellByColumnAndRow("10", $row)->getValue()) ;
echo '<br/>';
}
}
Could someone please let me know what I am doing incorrectly here?
In the PHP Developer Documentation, which I found through Google, they use Row- and Celliterators as follows:
$objWorksheet = $objPHPExcel->getActiveSheet();
foreach ($objWorksheet->getRowIterator() as $row) {
$cellIterator = $row->getCellIterator();
foreach ($cellIterator as $cell) {
$cell->getValue();
}
}
Using this you could use the following to compare it with the wanted value:
$check = $objPHPExcel->getActiveSheet()->getCellByColumnAndRow(10, $row)->getValue();
foreach ($objWorksheet->getRowIterator() as $row) {
$cellIterator = $row->getCellIterator();
foreach ($cellIterator as $cell) {
$value = $cell->getValue();
if($check == $value){
//what you want to happen, if it is true
} else {
//what you want to happen, if it is false
}
}
}
Discovered the value in the excel column is quoted_printable. I found out this by using following code:
foreach(mb_list_encodings() as $chr){
echo 'Row '. $row .'-'. mb_convert_encoding($var2, 'UTF-8', $chr)." : ".$chr."<br>";
}
this displays what encoding is for the value. My case was Quoted-Printable I found the solution here to encode quoted printable characters.

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

PHP: show only last data from same data on loop

i have data from php loop foreach like this
foreach ($query->result() as $row) {
echo $row->name;
}
how to make the result show only the end data without remove others if data has same (if data have same value, hide all except the last one) like this:
*sorry bad english, this is the first time i ask here. thank you
Online Check, This is just a demo example.
See below the real example:
At first you need to use array_search for get the position of the same data, if exist then just remove it using $arr[$pos] = '';, and each and every time you need to import data into the new array called $arr and after completing fetching data you need to use a foreach loop to print them.
$arr = array();
foreach($query->result() as $row){
$pos = array_search($row->name, $arr);
if($pos !== false)
$arr[$pos] = '';
$arr[] = $row->name;
}
foreach($arr as $val){
echo $val.'<br/>';
}
Check this and let me know.
The data_seek method might help. This assumes your array is reasonable ordered to begin with.
$rowCount = 0;
$res = $query->result();
foreach($res as $row) {
if ($rowCount < $res->num_rows - 1) {
// set internal pointer to next row
$res->data_seek($rowCount + 1);
// if the row names match, print an empty string
// otherwise print the current name
$nextRow = $res->fetch_row();
if ($row->name == $nextRow->name) {
echo "";
// reset the internal pointer
$res->data_seek($rowCount);
} else {
echo $row->name;
}
} else {
echo $row->name;
}
// update the row count
$rowCount += 1;
}

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