Getting cells by coordinate - php

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

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

How to dynamically add to PHPExcel spreadsheet

Alright, So I have this code
$key = $_SESSION['order_nums'];
$sqll = "SELECT * FROM `money` WHERE `order` = :key";
$qq=$con->prepare($sqll);
$qq->bindvalue(":key", $key);
$qq->execute();
$excel2 = PHPExcel_IOFactory::createReader('Excel2007');
$excel2 = $excel2->load('nTest.xlsx'); // Empty Sheet
$excel2->setActiveSheetIndex(0);
$worksheet = $excel2->getActiveSheet();
while($fdata=$qq->fetch(PDO::FETCH_ASSOC))
{
$worksheet
->setCellValue('A7', $fdata['code']);
}
Where it it setting the cell value for A7 there is about 6 more of those that match. When I do it like this however, It only puts its into the CELL A7
while($fdata=$qq->fetch(PDO::FETCH_ASSOC))
{
$worksheet
->setCellValue('A7', $fdata['code']);
}
How can I make it where
The above value will Drop down one cell for each new entry.
So the next would be A8, A9..... and so on.
That 'A7' isn't some kind of magic value, it's just a normal PHP string that's passed as a standard function argument to the setCellValue() method.... you can replace it with a string variable that you define yourself, and change for each row
$column = 'A';
$row = 7;
while($fdata=$qq->fetch(PDO::FETCH_ASSOC))
{
$worksheet
->setCellValue($column . $row, $fdata['code']);
$row++;
}
$row = 'A';
while($fdata=$qq->fetch(PDO::FETCH_ASSOC)){
$col = 1;
foreach($fdata as $data){
$worksheet->setCellValue("$row$col", $data);
$col++;
}
$row++;
}

Writing and Exporting Excel file Using PHPExcel

I am Trying to fill my Excel sheet with the data i filtered through the methods i have made. For now i am getting a sheet but i only have only one row filled not the other it's not getting the data i provide it though my object
I am trying my sheet something similar to this sheet .
i am trying to write code in this part of code :
public function export($Sets,$disp_filter)
{
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()->setTitle("Offic excel Test Document");
$styleArray = array(
'font' => array(
'bold' => true,
'color' => array('rgb' => 'FF0000'),
'size' => 10,
'name' => 'Verdana'
));
$objPHPExcel->getActiveSheet()->getStyle('A1')->applyFromArray($styleArray);
$excel_out = array($this->outputSampleName($Sets));
// var_dump($excel_out);
// exit;
$objPHPExcel->getActiveSheet()->SetCellValue('A1', 'Sample Size and Margin of Error');
$rowCount = 2;
foreach ($excel_out as $key=> $line)
{
$colCount = 'A';
$i=0;
// $line = array($Set['name']);
// $CT = $Set['crossTabs']['base'];
// $Moe = array($CT['sample']['moe']);
foreach($line as $col_value)
{
// var_dump($col_value);
// exit;
$objPHPExcel->getActiveSheet()->setCellValue($colCount.$rowCount, $col_value[$i])
->getStyle($colCount.$rowCount)->applyFromArray($styleArray);
$colCount++;
}
$rowCount++;
$i++;
}
return $objPHPExcel;
}
protected function outputSampleName($Sets)
{
foreach ($Sets as $Set)
{
$CT = $Set['crossTabs']['base'];
$line = array(
$Set['name'],
$CT['sample']['moe'] . '%'
);
$excel_out []= $line;
}
return $excel_out;
}
when i see by var_dump($excel_out)
i have this data structure :
**Please suggest me something how can i get those percentage values in my next row in optimized way.
for now i can only loop through the sample[name] which are (enthusiasts, hunter, new shooters etc. )from that array. **
thanks in advance
Maybe because your array elements are arrays themselves, and you are trying to place these subarrays into cells.
Try setting each element of $line in separate cells:
foreach ($excel_out as $line)
{
$colCount = 'A';
$objPHPExcel->getActiveSheet()
->setCellValue('A'.$rowCount, $line[0])
->setCellValue('B'.$rowCount, $line[1])
->setCellValue('C'.$rowCount, $line[2])
->setCellValue('D'.$rowCount, $line[3])
->setCellValue('E'.$rowCount, $line[4]);
$colCount++;
$rowCount++;
}
Note that the first sub-array in $excel_out has only one element. You may want to store.
You could also use an inner loop to traverse through each $line.
EDIT:
After looking at the code in your answer.
Using inner loop:
oreach ($excel_out as $key=> $line)
{
$colCount = 'A';
$i = 0;
foreach($line as $col_value)
{
// var_dump($col_value);
// exit;
$objPHPExcel->getActiveSheet()->setCellValue($colCount.$rowCount, $col_value[$i]);
//$objPHPExcel->getActiveSheet()->setCellValue('B'.$rowCount, $col_value[1]);
//$objPHPExcel->getActiveSheet()->setCellValue('C'.$rowCount, $col_value[2]);
//$objPHPExcel->getActiveSheet()->setCellValue('D'.$rowCount, $col_value[3]);
//$objPHPExcel->getActiveSheet()->setCellValue('E'.$rowCount, $col_value[4]);
//$objPHPExcel->getActiveSheet()->setCellValue('F'.$rowCount, $col_value[5]);
$colCount++;
$i++;
//$rowCount++;
}
$rowCount++;
// $colCount++;
}
$objPHPExcel->getActiveSheet()->setCellValue($colCount.$rowCount, $line);
Seems like you're writing an array $line into a cell. Should you do a loop from 0 to count($line) to put each element into a cell?

Categories