How to use Laravel Excel Library

Asked

Viewed 2,502 times

2

I have a .csv where I need to import your data into the database. I am using an Laravel library to import it.

What is this one: https://github.com/Maatwebsite/Laravel-Excel

In the code I’m doing like 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 take the test and is returning like this:

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

Being that he is:

Tabela CSV

I tried to change the parameters in the configuration file, but it didn’t work either.

'csv'        => array(
        /*
       |--------------------------------------------------------------------------
       | Delimiter
       |--------------------------------------------------------------------------
       |
       | The default delimiter which will be used to read out a CSV file
       |
       */

        'delimiter'   => ',',

        /*
        |--------------------------------------------------------------------------
        | Enclosure
        |--------------------------------------------------------------------------
        */

        'enclosure'   => '"',

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

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

In fact the documentation does not explain almost anything. Very little information.

1 - How to get the values of rows and columns ?

1 answer

4


I managed to solve. In my case I need to put header in the file .csv 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 managed 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');
        }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.