How to use the Laravel Excel Library

2

I have a .csv where I need to import your data into the database. To do the import I'm using a Laravel library.

What's in here: link

In the code I'm doing this:

<?php namespace App\Http\Controllers;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Excel;
use Illuminate\Http\Request;

class ImporterController extends Controller {

# Página de Importação da Lista de Produtos para Base de Dados
public function getIndex(){

    \Excel::load('public/upload/file.csv', function($reader) {

        // Getting all results
        $results = $reader->get();

        // ->all() is a wrapper for ->get() and will work the same
        $results = $reader->all();

        foreach ($results as $key => $var) {
            echo $var."<br>";
        }
    });
}

I'm using a small file .csv to do the test and it's returning like this:

  

{"100005anel_o": "100006; O" RING} {"100005anel_o": "100024; O"   {"100005anel_o": "100024; VITON RING \ n100494; GAXETA"}   {"100005anel_o": "100506; SEALER"} {"100005anel_o": "100540;   {"100005anel_o": "100552; SCRAPER"} {"100005anel_o": "100552; SCRAPER"}   {"100005anel_o": "100598; SEALER"} {"100005anel_o": "100653; SEALER"}

Being that it is like this:

Itriedchangingtheparametersintheconfigurationfile,butitdidnotworkeither.

'csv'=>array(/*|--------------------------------------------------------------------------|Delimiter|--------------------------------------------------------------------------||ThedefaultdelimiterwhichwillbeusedtoreadoutaCSVfile|*/'delimiter'=>',',/*|--------------------------------------------------------------------------|Enclosure|--------------------------------------------------------------------------*/'enclosure'=>'"',

        /*
        |--------------------------------------------------------------------------
        | Line endings
        |--------------------------------------------------------------------------
        */

        'line_ending' => "\r\n"
    ),

Actually the documentation explains almost nothing. Very scarce information.

1 - How do I get the values of rows and columns?

    
asked by anonymous 10.08.2015 / 22:45

1 answer

4

I managed to resolve. In my case I need to put header in the .csv file with the name of the columns. In this case they were Code and Product .

Then I read the documentation to implement in the code and I was able to bring the records.

        $fileCSV         = Request::file('arquivo');
        $destinationPath = 'upload/';
        $fileName        = $fileCSV->getClientOriginalName();
        $fileExtension   = $fileCSV->getClientOriginalExtension();

        # Verificar Extensão do Arquivo - Apenas .CSV
        if($fileExtension == 'csv'){
            # Faz o Upload Antes da Importação
            $fileCSV->move($destinationPath, $fileName);

            # Excel CSV To Base de Dados
            \Excel::load($destinationPath.'/'.$fileName, function($reader){
                # Lê os Dados
                $result                 = $reader->get();

                # Coloca Cada Linha Dentro de um Array
                $arrData[]              = '';
                foreach ($result as $key => $value) {
                    $arrData[] = $value[0];
                }

                # Limpa Array de Linhas Vazias
                $arrData                = array_filter($arrData);

                # Não Repete Códigos Iguais com Descrição Igual no Array
                $arrData                = array_unique($arrData);

                foreach($arrData as $foo => $linha){
                    # Explode em Array
                    $var                = explode(";", $linha);
                    $varCodigo          = $var[0];
                    $varDescricao       = $var[1];

                    $newProd            = new ListaProduto;
                    $newProd->codigo    = $varCodigo;
                    $newProd->produto   = $varDescricao;
                    $newProd->save();
                }
            });

            Session::flash('message-result', 'Produtos Adicionados com Sucesso.');
            return redirect('dashboard/produtos/listar');
        }
    
13.08.2015 / 18:16