How to get only one cell from a CSV file with PHP?

0

How do I get just one row from a specific column? In the code below it shows me all the rows and all the columns it has in the CSV file. I just want a specific cell.

Example:
Coluna B - Cars
Line 2 - Fox
Line and column cell - B2

I want to get only this B2 cell and print it on the screen.

<?php
// activar Error reporting
error_reporting(E_ALL);

// carregar a classe PHPExcel
require_once 'Classes/PHPExcel.php';

// iniciar o objecto para leitura
$objReader = new PHPExcel_Reader_CSV();$objReader->setInputEncoding('CP1252');
$objReader->setDelimiter(';');
$objReader->setEnclosure('');
$objReader->setSheetIndex(0);
$objPHPExcel = $objReader->load("itens.csv");

//Pegando o total de colunas
$colunas       = $objPHPExcel->setActiveSheetIndex(0)->getHighestColumn();
$total_colunas = PHPExcel_Cell::columnIndexFromString($colunas);

//Pegando o total de linhas
$total_linhas = $objPHPExcel->setActiveSheetIndex(0)->getHighestRow();

echo "<table border='1'>";
// navegar na linha
for($linha=1; $linha<= $total_linhas; $linha++){
    echo "<tr>";
    // navegar nas colunas da respactiva linha
    for($coluna=1; $coluna<= $total_colunas -1; $coluna++){
        if($linha==1){
        // escreve o cabeçalho da tabela
            echo "<th>".utf8_decode($objPHPExcel->getActiveSheet()->getCellByColumnAndRow($coluna, $linha)->getValue())."</th>";
        }else{
        // escreve os dados da tabela
            echo "<td>".utf8_decode($objPHPExcel->getActiveSheet()->getCellByColumnAndRow($coluna, $linha)->getValue())."</td>";
        }
    }
    echo "</tr>";
}
echo "</table>";
?>
    
asked by anonymous 30.06.2017 / 14:47

1 answer

0

Deconstruct the CSV by grabbing the column index by the first line and searching for the value by the line specified, for example, for the table:

1 | a  | b  | c  |
2 | AA | BB | CC |
3 | XX | YY | ZZ |

We want the value of cell B2, then:

$csv = "a,b,c\nAA,BB,CC\nXX,YY,ZZ";
$celula = array( 'b','2' );

// Crie um array com as linhas
$linhas = explode( "\n", $csv ); // array( 'a,b,c', 'AA,BB,CC', 'XX,YY,ZZ' );

// Crie um array com as colunas da primeira linha
$header = explode( ',', $linhas[0] ); // array( 'a', 'b, 'c' );

// Crie um array com as colunas da linha que vc quer buscar
$colunas_linha = explode( ',', $linhas[ $celula[1]-1 ] ); // array( 'AA', 'BB, 'CC' );

// Pegue o índice da coluna que você quer buscar pelo nome
$indice_coluna = array_search( $celula[0], $header, true ); // 1

// Depois pegue o valor da célula buscando o índice no array da coluna
echo $colunas_linha[$indice_coluna]; // 'BB'

ps: In the example numbering is not part of the table (as is common in CSV), I include only to make the view clearer

Functional sample

    
30.06.2017 / 15:29