PHPExcel Column Loop - php

How can I do a loop which based on Excel worksheet columns? I found (and used) WorksheetIterator, RowIterator and CellIterator but nothing about columns.

There is no ColumnIterator, so you'll have to do this by hand.
For any given worksheet:
To loop rows for a column:
$column = 'A';
$lastRow = $worksheet->getHighestRow();
for ($row = 1; $row <= $lastRow; $row++) {
$cell = $worksheet->getCell($column.$row);
// Do what you want with the cell
}
To loop columns in a row, you can take advantage of PHP's Perls-style ability to increment characters:
$row = 1;
$lastColumn = $worksheet->getHighestColumn();
$lastColumn++;
for ($column = 'A'; $column != $lastColumn; $column++) {
$cell = $worksheet->getCell($column.$row);
// Do what you want with the cell
}
Note that when comparing column letters to test for the last column in the loop, we can't simply use < or <= because we're comparing strings, and "B" > "AZ" in standard string comparison, so we use a != comparison, having incremented the highest column value to give the first column ID past the end point.
You can also use
$worksheet->cellExists($column.$row);
in the loop to test for the existence of a cell before accessing it using getCell() (or not) to emulate the iterator getIterateOnlyExistingCells() behaviour
The iterators are actually fairly slow, so you may well find these simple loops are faster than using the iterators.
UPDATE (2015-05-06)
PHPExcel version 1.8.1 has introduced a new Column Iterator. The Row and Column iterators also allows you to specify a range of rows or columns to iterate, and allow you to use prev() and well as next() when looping through

This short snippet provides loop throught rows of columns.
It gets the indexes of last non empty column (and its row) and loops to that indexes, so be aware of forgotten values in excel.
Code loops throught rows of column A, then rows of column B ...
$objReader = new PHPExcel_Reader_Excel2007();
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load($file);
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet)
{
$worksheetTitle = $worksheet->getTitle();
$highestColumn = $worksheet->getHighestColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
// expects same number of row records for all columns
$highestRow = $worksheet->getHighestRow();
for($col = 0; $col < $highestColumnIndex; $col++)
{
// if you do not expect same number of row records for all columns
// get highest row index for each column
// $highestRow = $worksheet->getHighestRow();
for ($row = 1; $row <= $highestRow; $row++)
{
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val = $cell->getValue();
// do what you want with cell value
}
}
}

loop columns as range
foreach ( range('A', $Excel->getActiveSheet()->getHighestColumn()) as $column_key) {
}

Try this! Work!
$limit = 10000;
$value='sua mensagem'
for($i=0,$j='A';$i<$limit;$i++,$j++) {
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue($j.$i, $value);
}
set in $value what you want print.

This is the fix for the getColumnLetter method of the last message, it allows you to get the "letters" of the columns, whatever the number of columns you have
function getColumnLetter( $number ){
$prefix = '';
$suffix = '';
$prefNum = intval( $number/26 );
if( $number > 25 ){
$prefix = getColumnLetter( $prefNum - 1 );
}
$suffix = chr( fmod( $number, 26 )+65 );
return $prefix.$suffix;
}

This recursive method was designed allows you to get the "letters" of the columns, whatever the number of columns you have, from "A" to "ZZZZZZZZZ..." :
function getColumnLetter( $number )
{
$prefix = '';
$suffix = '';
$prefNum = intval( $number/26 );
if( $prefNum > 25 )
{
$prefix = getColumnLetter( $prefNum );
}
$suffix = chr( fmod( $number, 26 )+65 );
return $prefix.$suffix;
}
So you can loop the columns of an PHP array on index number and convert it to a string of letters and use it in PHPExcel methods, like "setCellValue" ...
But solutions above are surely faster if you can use them !

In PhpSpreadsheet ( which replaces PHPExcel ) you can do:
foreach( $sheet->getColumnIterator() as $col )
{
$sheet->getColumnDimension( $col->getColumnIndex() )->setAutosize( true );
}

Related

Delete row phpexcel

I want to load my file.xls and check if my elements contains the character ^; then, I want to remove it.
Here my code so far:
$objPHPExcel = PHPExcel_IOFactory::load("trainbayes.xlsx");
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet){
$column = 'C';
$lastRow = $worksheet->getHighestRow();
for ($row = 2; $row <= $lastRow; $row++) {
$cell = $worksheet->getCell($column.$row);
if (preg_match("/([\^])/",$cell)){
$objPHPExcel->getActiveSheet()->removeRow($row,$row);
}
}
}
But it didn't work. Can you help me? Thank you :)
$cell = $worksheet->getCell($column.$row);
Returns a Cell object and assigns it to $cell; you are then treating that cell object as though it was a string in your preg_match() call.
Surely you should be checking the value of the cell
$cell = $worksheet->getCell($column.$row)->getValue();
Additionally,
$objPHPExcel->getActiveSheet()->removeRow($row,$row);
Do you really mean to pass $row twice? Second argument is the number of rows to delete, first argument is the row number to start deleting, so if you pass $row is 5, then PHPExcel will delete 5 rows, starting at row number 5.
Surely you mean
$objPHPExcel->getActiveSheet()->removeRow($row, 1);
or simply
$objPHPExcel->getActiveSheet()->removeRow($row);

Php to Excel : fill the output Excel file with a loop

I want to create an Excel file (with PhpExcel) and fill it with the content of a MySQL query.
I only have one column so the result will look like this :
$sheet->setCellValueByColumnAndRow(0, $i, $content)
So I have to loop inside my query and create a counter to fill each row corresponding to each item of the column ptlum of my content.
So the goal is to have the following result :
1 AX001
2 AX003
3 AX012
The code is the one :
$column = 1;
while($data = mysql_fetch_assoc($result)) {
$workbook = new PHPExcel;
$sheet = $workbook->getActiveSheet();
$sheet->setCellValueByColumnAndRow(0, $column, $data['ptlum']);
//echo($column. " " . $data['ptlum']. " ");
$column = $column + 1; //or $column++;
The problem is that my Excel file is empty..
If i put a number instead of $column in the setCellValueByColumnAndRow line it works. But the variable does not work..
On the other hand if I put "$column = 1;" inside the loop, my Excel file will always contain one only row..
Have you an idea ?
Thank you very much !
You just have to change the call to setCellValueByColumnAndRow for each column and increment it:
$sql = "SELECT ptlum FROM `ptlum` WHERE nomcom = 'AIGREFEUILLE' and RIGHT (date,4) < 2015 and RIGHT(date,4) > 0 ";
$result = mysql_query($sql);
$row = 1; // 1-based index
$column = 1;
while($data = mysql_fetch_assoc($result)) {
$sheet->setCellValueByColumnAndRow($column, $row, $data['ptlum']);
$column = $column + 1; //or $column++; if you prefer
}
As you see, you can retrieve the field/column you want with mysql_fetch_assoc, returning an associative array.
Also, you don't have to include the field(s) of your WHERE condition(s) in the SELECT.
Then finally, you should replace the deprecated mysql_* function by their equivalents mysqli_*, as explained here.
Edit:
For your "new" problem, this code should work:
$sql = "SELECT ptlum FROM `ptlum` WHERE nomcom = 'AIGREFEUILLE' and RIGHT (date,4) < 2015 and RIGHT(date,4) > 0 ";
$result = mysql_query($sql);
$row = 1; // 1-based index
$column = 1;
$workbook = new PHPExcel;
$sheet = $workbook->getActiveSheet();
while($data = mysql_fetch_assoc($result)) {
$sheet->setCellValueByColumnAndRow($column, $row, $data['ptlum']);
$column = $column + 1; //or $column++; if you prefer
}
First, don't instanciate your workbook and sheet in each loop, do it before, once.
Second, you had your arguments in the wrong order, it's column then row, not the inverse, as explicited in the method name.
Maybe this is the thing you wanted:
$sql = "SELECT ptlum, RIGHT(date,4) FROM `ptlum` WHERE nomcom = 'AIGREFEUILLE' and RIGHT (date,4) < 2015 and RIGHT(date,4) > 0 ";
$result = mysql_query($sql);
$i = 0;
while($data = mysql_fetch_assoc($result)) {
$sheet->setCellValueByColumnAndRow(0, $i, $i+1); //1-based index
$sheet->setCellValueByColumnAndRow(1, $i, $data['ptlum']);
$i++;
}

PHPExcel loop through rows and columns

Need help identifying weird problem that i'm facing. I did tried searching in stack overflow but didn't find any possible answer.
Here is sample program that works displaying all rows and columns on UI
<?php
date_default_timezone_set('America/Los_Angeles');
require_once 'PHPExcel-1.8/Classes/PHPExcel.php';
include 'PHPExcel-1.8/Classes/PHPExcel/IOFactory.php';
$path = 'demo.xlsx';
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
for ($row = 2; $row <= $highestRow; ++ $row) {
$val=array();
for ($col = 0; $col < $highestColumnIndex; ++ $col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val[] = $cell->getValue();
//End of For loop
}
$Col1 = $val[0] ;
$Col2 = $val[1] ;
$Col3 = $val[2];
echo $Col1;
echo $Col2;
echo $Col3;
echo "<br>";
//End of for loop
}
?>
This program works perfectly fine printing all columns and rows for n-lenght
Problem - Now our requirement is to get values of Col1, Col2, Col3 and using mysql_query compare into database and do further action.
Minute we add anything above //End of for loop. It only iterates once and stops without throwing any php errors.
e.g.
.....
echo $Col1;
echo $Col2;
echo $Col3;
echo "<br>";
**$sql = mysql_query("select COALESCE(MAX(SrNo), 0) AS Max_No from TABLEA where ColumnA = 1 and ColumnB = '$Col3'");
$row = mysql_fetch_array($sql);
echo $row["Max_No"];**
//End of for loop
}
?>
If we add above SQL the same program only iterates once and stops? It doesn't show any errors in logs or on screen.
Thanks in advance for your help!.
If you try to iterate with for ($col = 2; $col <= $highestColumn; ++ $col){...} it will work for columns from A to Z, but it fails pass the Z (Ex. iterate between 'A' to 'AB').
In order to iterate pass 'Z', you need to convert the column to integer, increment, compare, and get it as string again:
$MAX_COL = $sheet->getHighestDataColumn();
$MAX_COL_INDEX = PHPExcel_Cell::columnIndexFromString($MAX_COL);
for($index=0 ; $index <= $MAX_COL_INDEX ; $index++){
$col = PHPExcel_Cell::stringFromColumnIndex($index);
// do something, like set the column width...
$sheet->getColumnDimension($col)->setAutoSize(TRUE);
}
With this, you easy iterate pass the 'Z' column.
As you're using the same variable $row for the row number in the Excel iteration and for the result of your select query, it's not surprising that you're running into problems.....
The integer value that holds the Excel row number is being overwritten by the array that you get from your SQL query, and then you're trying to use that result array as the next Excel row number
Solution: Use a different variable for these two elements.
$rowData = mysql_fetch_array($sql);
echo $rowData["Max_No"];**

Rows and columns in 2D array [duplicate]

I have a two dimensional array with unknown number of elements.
$two_darray[row][column]; //there will be an unknown integer values instead of row and column keywords
If I were to write a for loop as follows, how can I determine how many rows and columns in my $two_darray. Can you please tell me if there is a library function in php that can tell me the value inside [????] [????]
for($row=0; $row<………; $row++)
{
for($column =0; $column <………; $ column ++)
{
echo $two_darray[$row][$column];
}
echo “\n end of one column \n”;
}
I really need to know the value of rows and columns in order to perform other calculations.
foreach ($two_darray as $key => $row) {
foreach ($row as $key2 => $val) {
...
}
}
No need to worry about how many elements are in each array, as foreach() will take care of it for you. If you absolutely refuse to use foreach, then just count() each array as it comes up.
$rows = count($two_d_array);
for ($row = 0; $row < $rows; $row++) {
$cols = count($two_darray[$row]);
for($col = 0; $col < $cols; $col++ ) {
...
}
}
This is what i do:
My superheroes' array:
$superArray[0][0] = "DeadPool";
$superArray[1][0] = "Spiderman";
$superArray[1][1] = "Ironman";
$superArray[1][2] = "Wolverine";
$superArray[1][3] = "Batman";
Get size :
echo count( $superArray ); // Print out Number of rows = 2
echo count( $superArray[0] ); // Print Number of columns in $superArray[0] = 1
echo count( $superArray[1] ); // Print Number of columns in $superArray[1] = 4
php
For a php Multidimensional Array, Use
$rowSize = count( $arrayName );
$columnSize = max( array_map('count', $arrayName) );
If you need to know an actual number, then you can use the sizeof() or count() functions to determine the size of each array element.
$rows = count($two_darray) // This will get you the number of rows
foreach ($two_darray as $row => $column)
{
$cols = count($row);
}
the quick way for normal,non-mixed 2-dim Array,
$Rows=count($array);
$colomns=(count($array,1)-count($array))/count($array);
for a php indexed two-dimensional array:
$arName = array(
array(10,11,12,13),
array(20,21,22,23),
array(30,31,32,33)
);
$col_size=count($arName[$index=0]);
for($row=0; $row<count($arName); $row++)
{
for($col=0; $col<$col_size; $col++)
{
echo $arName[$row][$col]. " ";
}
echo "<br>";
}
Output:
10 11 12 13
20 21 22 23
30 31 32 33

In php, Number of rows and columns in a 2 D array?

I have a two dimensional array with unknown number of elements.
$two_darray[row][column]; //there will be an unknown integer values instead of row and column keywords
If I were to write a for loop as follows, how can I determine how many rows and columns in my $two_darray. Can you please tell me if there is a library function in php that can tell me the value inside [????] [????]
for($row=0; $row<………; $row++)
{
for($column =0; $column <………; $ column ++)
{
echo $two_darray[$row][$column];
}
echo “\n end of one column \n”;
}
I really need to know the value of rows and columns in order to perform other calculations.
foreach ($two_darray as $key => $row) {
foreach ($row as $key2 => $val) {
...
}
}
No need to worry about how many elements are in each array, as foreach() will take care of it for you. If you absolutely refuse to use foreach, then just count() each array as it comes up.
$rows = count($two_d_array);
for ($row = 0; $row < $rows; $row++) {
$cols = count($two_darray[$row]);
for($col = 0; $col < $cols; $col++ ) {
...
}
}
This is what i do:
My superheroes' array:
$superArray[0][0] = "DeadPool";
$superArray[1][0] = "Spiderman";
$superArray[1][1] = "Ironman";
$superArray[1][2] = "Wolverine";
$superArray[1][3] = "Batman";
Get size :
echo count( $superArray ); // Print out Number of rows = 2
echo count( $superArray[0] ); // Print Number of columns in $superArray[0] = 1
echo count( $superArray[1] ); // Print Number of columns in $superArray[1] = 4
php
For a php Multidimensional Array, Use
$rowSize = count( $arrayName );
$columnSize = max( array_map('count', $arrayName) );
If you need to know an actual number, then you can use the sizeof() or count() functions to determine the size of each array element.
$rows = count($two_darray) // This will get you the number of rows
foreach ($two_darray as $row => $column)
{
$cols = count($row);
}
the quick way for normal,non-mixed 2-dim Array,
$Rows=count($array);
$colomns=(count($array,1)-count($array))/count($array);
for a php indexed two-dimensional array:
$arName = array(
array(10,11,12,13),
array(20,21,22,23),
array(30,31,32,33)
);
$col_size=count($arName[$index=0]);
for($row=0; $row<count($arName); $row++)
{
for($col=0; $col<$col_size; $col++)
{
echo $arName[$row][$col]. " ";
}
echo "<br>";
}
Output:
10 11 12 13
20 21 22 23
30 31 32 33

Categories