How to search and read excel file in php - 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;
}
}
}
}
}
?>

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
}
}

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

PHPExcel search cell by value

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.

Searching a CSV With PHP

I have a large CSV file. The first column contains the name of a processor. The second, the processor's benchmark score. EG:
Intel Pentium Dual T3400 # 2.16GHz,1322
Using a PHP script, I would like to search the first column for a string (EG. Pentium Dual T3400), and (assuming that there is only one result per search, else return an error message) create a variable containing the value of the second column.
I don't know if this will help, but I was sort of hoping it would look a little like this:
$cpuscore = csvsearch(CSV_file,query_string,column#_to_search,column#_to_return)
Where $cpuscore would contain the score of the processor name that matches the search query.
Feel free to suggest something that would produce similar results. I have MySQL, but I don't have the permissions to import tables from CSV.
You can use the php function fgetcsv(), http://php.net/manual/en/function.fgetcsv.php to traverse the csv file row by row. For instance:
$ch = fopen($path_to_file, "r");
$found = '';
/* If your csv file's first row contains Column Description you can use this to remove the first row in the while */
$header_row = fgetcsv($ch);
/* This will loop through all the rows until it reaches the end */
while(($row = fgetcsv($ch)) !== FALSE) {
/* $row is an array of columns from that row starting at 0 */
$first_column = $row[0];
/* Here you can do your search */
/* If found $found = $row[1]; */
/* Now $found will contain the 2nd column value (if found) */
}
I like to iterate through each line of a csv file and find the words i'm looking for, and compile a result from there. Here's something to get you started:
<?php
$query = "Intel Core i7 3600M"
$file = file('db.csv');
foreach($file as $value) {
if(stristr($value,$query)){
$items = explode(",", $value); echo $items[1];
};
};
?>

Categories