I am trying to find the last cells value of a row in an Excel table by the first cells value using PHPExcel. The user enters the value of the first cell in the row (which is the "command" parameter) and if it exists in the table my function is supposed to jump to the last cell of the row and return the value. This is my code:
public function search($command, $excelobj) {
foreach ($excelobj->getWorksheetIterator() as $worksheet) {
foreach ($worksheet->getRowIterator() as $row) {
$rowiterator = $worksheet->getRowIterator();
foreach ($row->getCellIterator() as $cell) {
$celliterator = $row->getCellIterator();
$head = $celliterator->current()->getValue();
if(strcmp($head, $command)) {
for ($i = 0; $i == 8; $i++) {
$celliterator->next();
}
return $cell->getValue();
}
}
}
}
return false;
}
For some reason it always returns wrong.
I solved it myself, this code functions correctly:
public function search($command, $excelobj) {
foreach ($excelobj->getWorksheetIterator() as $worksheet) {
foreach ($worksheet->getRowIterator() as $row) {
$rowiterator = $worksheet->getRowIterator();
$celliterator = $row->getCellIterator();
$celliterator->setIterateOnlyExistingCells(true);
$head = $celliterator->current()->getValue();
while (strcmp($head, $command) !== 0 && $rowiterator->valid()) {
$rowiterator->next();
$row = new PHPExcel_Worksheet_Row($worksheet, $rowiterator->key());
$celliterator = $row->getCellIterator();
$head = $celliterator->current()->getValue();
}
for ($i = 0; $i <= 7; $i++) {
$celliterator->next();
}
return $celliterator->current()->getValue();
}
}
return false;
}
Related
I have the following iterration:
foreach ($filelines as $indexrow => $line) {
$columns = explode($splitter, $line);
$row = [];
foreach ($columns as $columnindex => $column) {
$column = $this->prepareValue($column);
if (RegexValidation::isNum($column)) {
$row[] = $this->setValue('num', $column, $indexrow, $columnindex);
} else {
if (RegexValidation::isMMYY($column)) {
$row[] = $this->setValue("mmyy", $column, $indexrow, $columnindex);
} else {
if (RegexValidation::isZip($column)) {
$row[] = $this->setValue("zip", $column, $indexrow, $columnindex);
}
}
}
}
$dataset[$indexrow] = $row;
}
I need to fill $row in a specific sequence, first is "zip," then "mmyy," then "num," etc. If there is no field, fill it as empty.
How to do this in the existing loop? Now I have a solution sort result array, but It needs to loop again.
I would use a special key and sort by the key. And - there is an elseif.
foreach ($filelines as $indexrow => $line) {
$columns = explode($splitter, $line);
$row = [];
foreach ($columns as $columnindex => $column) {
$column = $this->prepareValue($column);
$counter = 0;
if (RegexValidation::isNum($column)) {
$row['C_'.$counter++] = $this->setValue('num', $column, $indexrow, $columnindex);
} elseif (RegexValidation::isMMYY($column)) {
$row['B_'.$counter++] = $this->setValue("mmyy", $column, $indexrow, $columnindex);
} elseif (RegexValidation::isZip($column)) {
$row['A_'.$counter++] = $this->setValue("zip", $column, $indexrow, $columnindex);
} else { // If there is no field, fill it as empty
$row['Z_'.$counter++] = '';
}
}
ksort($row);
$dataset[$indexrow] = array_values($row);
}
Use A for the group you want to have first, then B for the group you want next, and so on. If you want to preserve the order within the group, you should have leading zeros on the counter, because A_10 ist sorted before A_9. Change that to A_09, or A_000009 depending on the size of your dataset.
I have a excel file which contains certain rows with color i want to get the row id of a particular color code but unable to do it .. already searched but found nothing below is my code for PHPEXCEL
$cellColor = $objPHPExcel->getActiveSheet()->getStyle($cell->getCoordinate())->getFill()->getStartColor()->getRGB();
This will give me the color code and for the value i have $cell->getValue() where $cell is some variable for $cellIterator
foreach ($worksheet->getRowIterator() as $row) {
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false);
foreach ($cellIterator as $cell)
{
$cellColor = $objPHPExcel->getActiveSheet()->getStyle($cell->getCoordinate())->getFill()->getStartColor()->getRGB();
if (!empty($cell->getCalculatedValue())) {
if ($cellColor == 'yellow') {
echo ($cellColor.'======'.$cell->getValue());
}
}
}
}
$cell->getValue() will give me the value of that particular color code But, the problem is if i have 2 rows with color yellow then $cell->getValue() will give two value like 0-> yellow1 1-> yellow2 but after deleting the 1st yellow colour data in excel then result will be 0-> yellow2 which is wrong what i need is 0->'' 1-> yellow2 Thats why i need row id for that particular color so that i can identify the row.
After hours of practicing got my expected result
$objPHPExcel = PHPExcel_IOFactory::load('someFile.xls');
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
//$worksheetTitle = $worksheet->getTitle();
$highestRow = $worksheet->getHighestRow();
$highestColumn = $worksheet->getHighestColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
//$nrColumns = ord($highestColumn) - 64;
$groupCount = array();
$standardSetCount = array();
$standardCount = array();
$learningTargetCount = array();
for ($row = 1; $row <= $highestRow; ++$row) {
for ($col = 0; $col < $highestColumnIndex; ++$col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$colorCode = $objPHPExcel->getActiveSheet()->getStyle($cell->getCoordinate())->getFill()->getStartColor()->getRGB();
/*
* Yellow
*/
if ($colorCode == 'FFFF00') {
$val = $cell->getValue();
//$dataType = PHPExcel_Cell_DataType::dataTypeForValue($val);
$groupCount[] = $val; // $groupCount[] = $dataType;
}
/*
* gold
*/
if ($colorCode == 'CC9900') {
$val = $cell->getValue();
$standardSetCount[] = $val;
}
/*
* red
*/
if ($colorCode == 'FF3333') {
$val = $cell->getValue();
$standardCount[] = $val;
}
/*
* green
*/
if ($colorCode == '00CC33') {
$val = $cell->getValue();
$learningTargetCount[] = $val;
}
}
}
$group = (array_chunk($groupCount, $highestColumnIndex));
$standardSet = (array_chunk($standardSetCount, $highestColumnIndex));
$standard = (array_chunk($standardCount, $highestColumnIndex));
$learningTarget = (array_chunk($learningTargetCount, $highestColumnIndex));
echo '<pre>';
print_r($learningTarget);
}
I wrote a class to export excel files with a worksheet for each query passed to it.
For some reason my worksheets are missing the first row of results. The headers show up properly, but the first row under the header is missing.
If I DO NOT call the SetHeaderCells() function the first row is there, so I know it is something in my class.
SetHeaderCells() NOT called:
But if I do call the SetHeaderCells() then the first row is missing.
Calling this class with:
if(gfQSGetGetVar('Export')=='xls') {
$ex2 = new ExportToExcel2('Somefile');
$ex2->AddSheet('Sheet1', 'Select * from Division;');
$ex2->AddSheet('Sheet2', 'Select * from Zone');
$ex2->ExportMultiSheet();
}
Class:
require_once 'PhpExcel.php';
class ExportToExcel2 {
public $AllSheetData = [];
protected $SheetData = [];
protected $PHPExcel = '';
protected $FileName = '';
function __construct($_filename) {
$this->FileName = $_filename;
$this->PHPExcel = new PHPExcel;
//clean the output buffer before download
ob_clean();
}
public function AddSheet($_WorkSheetName, $_Query) {
$this->SheetData['Sheet_Name'] = $_WorkSheetName;
$this->SheetData['Query'] = $_Query;
$this->AllSheetData[] = $this->SheetData;
unset($this->SheetData);
}
public function ExportMultiSheet($_ExportType='xls') {
if(!empty($this->AllSheetData)) {
$count=0;$Result='';
$this->PHPExcel->setActiveSheetIndex(0);
foreach($this->AllSheetData as $subarray) {
if($count>0){
$this->PHPExcel->createSheet(null);
$this->PHPExcel->setActiveSheetIndex($count);
}
$count++;
foreach($subarray as $key => $value) {
if($key == 'Query') {
$Result = dbQuery($value);
$this->SetHeaderCells($Result);
$this->SetbodyCells($Result);
}
if($key =='Sheet_Name') {
$this->PHPExcel->getActiveSheet()->setTitle($value);
}
}
}
$this->ExportType($_ExportType);
}
}
public function ExportSingleSheet($_Query, $_ExportType='xls') {
$Result = dbQuery($_Query);
$this->SetHeaderCells($Result);
$this->SetBodyCells($Result);
$this->SetProperties();
$this->ExportType($_ExportType);
}
private function ExportType($_ExportType) {
if($_ExportType=='xls') {
$this->DownloadXLS();
}
else if($_ExportType=='csv') {
$this->DownloadCSV();
}
}
private function SetProperties() {
//set all columns to align left
$this->PHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
//show gridlines?
$this->PHPExcel->getActiveSheet()->setShowGridlines(true);
//set columns a through z to auto width
for($col = 'A'; $col !== 'Z'; $col++) {
$this->PHPExcel->getActiveSheet()
->getColumnDimension($col)
->setAutoSize(true);
}
//set the first sheet to open first
$this->PHPExcel->setActiveSheetIndex(0);
}
private function DownloadXLS() {
$this->SetProperties();
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'.$this->FileName.'-'.date("y.m.d").'.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($this->PHPExcel, 'Excel2007');
$objWriter->save('php://output');
exit;
}
private function DownloadCSV() {
$this->SetProperties();
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename="'.$this->FileName.'-'.date("y.m.d").'.csv"');
header('Cache-Control: max-age=0');
$objWriter = new PHPExcel_Writer_CSV($this->PHPExcel);
$objWriter->save("php://output");
exit;
}
private function SetHeaderCells($Result) {
$row = 1; // 1-based index
$row_data = sqlsrv_fetch_array($Result, SQLSRV_FETCH_ASSOC);
$col = 0;
foreach(array_keys($row_data) as $key) {
$this->PHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $key);
$col++;
}
}
private function SetBodyCells($Result) {
$row2 = 2;
while($row_data = sqlsrv_fetch_array($Result, SQLSRV_FETCH_ASSOC)) {
$col2 = 0;
foreach($row_data as $key=>$value) {
$this->PHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col2, $row2, $value);
$col2++;
}
$row2++;
}
}
}
Solved!
The way I resolved this was to use the recommended Metadata function.
Changed the SetHeaderCells function to this:
private function SetHeaderCells($Result) {
$row = 1; // 1-based index
$col = 0;
foreach( sqlsrv_field_metadata($Result) as $fieldMetadata ) {
foreach( $fieldMetadata as $name => $value) {
if($name=='Name') {
$this->PHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $value);
$col++;
}
}
}
}
You're fetching the first record and using the $row_data keys to set headers; but then that record has already been fetched, so when you move on to the data you're immediately going into a fetch loop that will start with the second record in your resultset
I don't believe sqlsrv supports a rewind function, but can you perhaps use sqlsrv_field_metadata() to get the header information rather than fetching the first record.
Alternatively, something like:
private function SetHeaderCells($Result) {
$row = 1; // 1-based index
$row_data = sqlsrv_fetch_array($Result, SQLSRV_FETCH_ASSOC);
$col = 0;
foreach(array_keys($row_data) as $key) {
$this->PHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $key);
$col++;
}
return $row_data;
}
private function SetBodyCells($Result, $row_data) {
$row2 = 2;
do {
$col2 = 0;
foreach($row_data as $key=>$value) {
$this->PHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col2, $row2, $value);
$col2++;
}
$row2++;
} while($row_data = sqlsrv_fetch_array($Result, SQLSRV_FETCH_ASSOC));
}
$Result = dbQuery($_Query);
$firstRow = $this->SetHeaderCells($Result);
$this->SetBodyCells($Result, $firstRow);
but using the metadata for the headings would be a better approach
$val = array();
foreach ($value as $key) {
$nested = $this->Mdl_mymodel->arr($key);
if($nested != NULL) {
$n = 0;
foreach ($nested as $nest) {
$n++;
$val[$n] = $nest->num;
}
}
else {
$val = '';
}
print_r($val);
}
print_r($val);
Here $val inside the loop is printed but outside it is empty. I think i am missing something. Please help!
Note: I am using codeigniter.
$val = array();
foreach ($value as $key) {
$nested = $this->Mdl_mymodel->arr();
if($nested != NULL) {
$n = 0;
foreach ($nested as $nest) {
$n++;
$val[$n] = $nest->num;
}
}
else {
// $val = ''; Commented this line because you have already
// initialized $val. If you do not get records,
// it will return as blank array.
}
print_r($val);
}
print_r($val);
I'm using PHPExcel, I have an multidimensional array called $sheetData. I want to be able to search the array for string D650.
For example if the string D650 is in $sheetData[12][E] I want it to return [12][E]. I can't seem to find a search function for PHPExcel. I've tried the code below but I am only getting one value back I need all the values. If the code isn't the best way to go about this please let me know. Thanks
function searchForId($id, $array) {
foreach ($array as $key => $val) {
$letter = "A";
for($i = 1; $i<= 26; $i++)
{
if ($val[$letter] === $id) {
return $key;
}
$letter++;
}
}
return null;
}
$id = searchForId('Denter code here650', $sheetData);
echo $id;
function searchForId($id, $array) {
foreach ($array as $row => $val) {
$letter = "A";
for($i = 1; $i<= 26; $i++) {
if ($val[$letter] === $id) {
return '[' . $row .'][' . $letter . ']';
}
$letter++;
}
}
return null;
}
though it might be more useful returning an array of row and column
function searchForId($id, $array) {
foreach ($array as $row => $val) {
$letter = "A";
for($i = 1; $i<= 26; $i++) {
if ($val[$letter] === $id) {
return array(
'row' => $row,
'column' => $letter
);
}
$letter++;
}
}
return null;
}