PHPExcel search cell by value - php

I'm wondering, how it's possible to help with such issue.
Let's say, I have an excel with such info in it (it could be much more info):
**Country** **Currency**
Germany EUR
USA USD
Russia RUB
and I'm entering in input form "USA", and I want to see the result USD from excel.
Is there some kind of function in PHP, which allows to search for a value in excel?
Or at least, if there existing such function, which returns in which cell (e.g. B2) such value exists?

There's nothing built-in to PHPExcel to do a search, but it's pretty straightforward to write something yourself based around the iterators.... take a look at 28iterator.php in /Examples
$foundInCells = array();
$searchValue = 'USA';
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
$ws = $worksheet->getTitle();
foreach ($worksheet->getRowIterator() as $row) {
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(true);
foreach ($cellIterator as $cell) {
if ($cell->getValue() == $searchValue) {
$foundInCells[] = $ws . '!' . $cell->getCoordinate();
}
}
}
}
var_dump($foundInCells);
Of course, if you're only wanting to search a specific column in a specific worksheet, you can simplify this a great deal, e.g. using rangeToArray() and then searching the array using standard PHP array functions.

As there a re many different Excel Formats (2003, 2010 quirks, ooxml, etc.) you will have to look for a third party library to read excel files.
Find some examples in this question or in this question.
Edit: added a more current question.

Related

How do you read cells in PhpOffice\PhpSpreadsheet using the IReadFilter in PHP?

I am trying to read two columns from a spreadsheet across multiple sheets. An example of this would be:
Sheet One: Sheet Two: Sheet Three: ETC...
A ..... V A ..... V A ..... V <-- Two Columns I need
1 5 32 9 54 1 <-- Rows Below
2 8 33 2 55 3
3 9 34 7 56 8
So far, I am loading the Spreadsheet using PhpOffice\PHPSpreadsheet and the documentation to learn how to do this.
After compiling all the information from the documentation together, I have come up with this:
class CustomXlsxReader implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter
{
public function readCell($column, $row, $worksheetName = '') {
return in_array($column, range('A','V'));
}
}
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
$reader->setLoadSheetsOnly(["A Coy", "B Coy", "C Coy", "S Coy", "HQ Coy"]);
$reader->setReadDataOnly(true);
$reader->setReadFilter(new CustomXlsxReader());
$spreadsheet = $reader->load($_FILES['xlsxFile']['tmp_name']); // I do not want to physically save the file as the data will be converted to a database for further distribution
I tried to find the reading cell section of the documentation and found this:
$worksheet = $spreadsheet->getActiveSheet(); // Not sure how to change between these
foreach ($worksheet->getRowIterator() as $row) {
$cellIterator = $row->getCellIterator();
foreach ($cellIterator as $cell) {
$cell = $cell->getValue(); // Not sure what column this is looping through
}
}
I can see that the \PhpOffice\PhpSpreadsheet\Reader\IReadFilter has the method to read the rows, however, the $spreadsheet instance does not have this method and I can not, for the life of me, find how to use this in the documentation.
How can I now read columns A and V from each sheet within my spreadsheet? I want to loop through the sheets (A coy, B coy, etc...) and read the columns A and V for each. array_merge would not conflict with any data so if its not possible to specifically read sheet by sheet, then a merged solution would be great also.
Many thanks in advance.
The spreadsheet doesn't have these methods, because they're accessed in the Reader, not in the Spreadsheet; the ReadFilter is simply telling the Reader to load only cell data for columns A-V when it reads the file into the Spreadsheet object
$worksheet = $spreadsheet->getActiveSheet(); // Not sure how to change between these
// Use `setActiveSheetIndex(<worksheetindex>)`
// or `setActiveSheetIndexByName(<worksheetname>)
// to set the selected worksheet
foreach ($worksheet->getRowIterator() as $row) {
$cellIterator = $row->getCellIterator();
foreach ($cellIterator as $cell) {
$cell = $cell->getValue(); // Not sure what column this is looping through
// The $cell->getColumn() method will tell you the column
}
}

How to search and read excel file in php

I would like someone to help me find a solution to my two problems: I have an excel file with 2 columns (A and B)
Column A contains barcode numbers that I must assign to an order number (in column B). Below an example:
COLUMN A....................COLUMN B
barcode.........................order number
12345678*******************35098
98765432 ******************35433
45454545
66554433
98766334 *******************43221
What I am looking for is the following:
from a given order number (in a variable), I would like to know if it exists in column B, if yes, I would like to recover its bar code.
If it does not exist, I would like to add this order number in one of the empty cells in column B and then retrieve the barcode that has been assigned to it.
All this using PHPExcel ... I tried some, but I'm blocking ... If anyone could help me, I'd be very grateful to him.
Thank you
PS: A small precision, if you have to know the number of non-empty line of column A, we will say that there are 1000 lines
Here what I did. This code only check if the order number exist. But I'm not sure if this is the best way:
with this code, I know if the ordernumber exist in file.
My problem now is how to get the bar code number if the ordernumber exist in column B, or if it doesn't exist, how to add the order number in one of the empty cells and retrieve the corresponding barcode
Thanks to everyone for your help
<?php
$orderNumber = 12341;
function searchOrder ($num){
/** PHPExcel_IOFactory */
require_once 'Classes/PHPExcel/IOFactory.php';
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objPHPExcel = $objReader->load("barreCode_ordernumber.xlsx");
$foundInCells = array();
$ordernumber = $num;
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
foreach ($worksheet->getRowIterator() as $row) {
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false);
foreach ($cellIterator as $cell) {
$numligne = $cell->getRow();
$numcolonne = $cell->getColumn();
if ($cell->getValue() == $ordernumber) {
return true;
}
}
}
}
}
?>

PHPExcel - Proceed if sheet name equals

Here's the scenario, I want to be able to run a specific section of PHP code for each different excel sheet, so basically if I have a workbook that has the following sheets, "Funds", "Accounts", "Spending Data", how can I look through each sheet to be able to run separate code depending on the sheet name, so for example, I only want to fetch the cell data from A5:D5 on "Funds", but on "Accounts" I want to get the A5:P5, etc.
I've tried using the foreach ($objPHPExcel->getWorksheetIterator() as $worksheet), but that just loops through each sheet, which I would expect it to do then runs the same code on each sheet which is not what I'm looking for.
Sorry if I've not explained it very well, but if there was someway I could do something like;
if sheetname == "Funds" {
//get cells A5:D5
}
if sheetname == "Accounts" {
//get cells A5:P5
}
etc...
Any help would be greatly appreciated.
Many thanks in advance.
Kind regards.
Use getTitle to know the sheet's title:
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet)
{
$sheetname = $worksheet->getTitle();
if ($sheetname == "Funds")
{
//get cells A5:D5
}
if ($sheetname == "Accounts")
{
//get cells A5:P5
}
}

Search a cell by string in PHPExcel

I want to know if it's possible to get a cell by its name in an xls document, I mean Ii have this info in a excel file:
Normally to get the coordinate of the cell with the value "ASUS"
$objPHPExcel->getActiveSheet()->getCell('B3')->getValue();
my problem is that users send my this excel file, and sometimes the rows are in disorder, e.g the row B3 sometimes appear in a different row like "B6" or "B7" or "B5", how I can get the cell "ASUS" getting by cell name "Modelo"
There is nothing built-in to PHPExcel to do a search, but using the following example, it can do well for your problem.
$foundInCells = array();
$searchTerm = 'ASUS';
foreach ($objPHPExcel->getWorksheetIterator() as $CurrentWorksheet) {
$ws = $CurrentWorksheet->getTitle();
foreach ($CurrentWorksheet->getRowIterator() as $row) {
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(true);
foreach ($cellIterator as $cell) {
if ($cell->getValue() == $searchTerm) {
$foundInCells[] = $ws . '!' . $cell->getCoordinate();
}
}
}
}
var_dump($foundInCells);
You'd have to loop through the entire file to find it just like searching a value in a 2D array.
Take a look at this answer

PHP: Taking Array (CSV) And Intelligently Returning Information

Hey Everyone. I'm a first time poster, but I've browsed this site a number of times. I have a coding issue that I'm not sure exactly how to solve. First I'll explain what I need to do, and what information I have, and I hope somebody can give me a nudge in the right direction.
What I have is a spreadsheet (CSV) that has the following info: Zone Name, Zip Code, City Name. One zone should have many cities that fall under it, and every city most likely has many zip codes that fall under it. For example:
Zone H, 92603, Irvine
Zone H, 92604, Irvine
Zone J, 92625, Corona
etc.
Okay, now that that's out of the way, here's what I need to do with this info. I need to be able to input a city name and have it return to me all zip codes that fall under that city, as well as the zone that the city lies in. For example, if I input Chatsworth, it should give me (Zone X) and (12345, 12346, 12347) as the zip codes (just an example).
I'm not sure the best way to go about this. I could create a MySQL database and work from there, or just work from .csv files, or hardcode it into the PHP file. I don't know how to search for a value in an array column, and then return the other columns accordingly (especially with multiple zip codes per city).
If anybody can help me out, it would be greatly appreciated. Also, feel free to let me know if you need more information from me. Thanks in advance to everyone reading.
If you want to pursue the CSV approach, then the first step is reading the file into a 2D array:
$csv = array_map("str_getcsv", file("file.csv"));
Now this is an indexed array, where you need to know which column is which. But if you know the city is always in [2] then searching for the other information becomes simple:
foreach ($csv as $i=>$row) {
if ($row[2] == "Chatsworth") {
$zone = $row[0];
$zip = $row[1];
break;
}
}
Ideally you would put this into a function, so you can call it multiple times. It would be easiest if you make it configurable which column to search, and just have it return the complete found row.
Okay so if you don't know where the $city name is in, then I would propose following utility function:
function search_csv($city) {
global $csv; // pre-parsed array (can be parameter though)
foreach ($csv as $i=>$row) {
if (in_array($city, $row)) {
$result_rows[] = $row;
}
}
return $result_rows;
}
function search_zip($city) {
$rows = search_csv($city);
foreach ($rows as $i=>$row) {
$rows[$i] = end(array_filter($row, "is_numeric"));
}
return $rows;
}
The first one returns a list of $rows which match. I'll leave it up to you how to figure out which column contains which. Only for the zip code it's kind of possible to return the results deterministically.
Zone H, 92603, Irvine
Zone H, 92604, Irvine
Zone J, 92625, Corona
etc.
you can take the file and get all its contents. then split it up by new line:
$searchCity = 'Searched'; //or whatever city you are looking for
$file = file_get_contents('file.csv');
$results = array();
$lines = explode("\n",$file);
//use any line delim as the 1st param,
//im deciding on \n but idk how your file is encoded
foreach($lines as $line){
//split the line
$col = explode(",",$line);
//and you know city is the 3rd element
if(trim($col[2]) == $searchCity){
$results[] = $col;
}
}
and at the end u have an array of the results like this:
$results = array(
array('Zone B', '12345', 'Searched'),
array('Zone Z', '35145', 'Searched'),
array('Zone Q', '12365', 'Searched'),
)

Categories