Worldscope

Import Export to Excel and CSV using Maatwebsite in Laravel 5

Palavras-chave:

Publicado em: 27/08/2025

Import and Export to Excel/CSV using Maatwebsite in Laravel 5

This article demonstrates how to implement import and export functionality for Excel and CSV files in Laravel 5 applications using the Maatwebsite Excel package. We will cover installation, configuration, code examples, and discuss alternative approaches.

Fundamental Concepts / Prerequisites

Before proceeding, you should have a basic understanding of the following:

  • Laravel framework: Familiarity with Laravel's routing, controllers, and models.
  • Composer: A dependency management tool for PHP.
  • PHP: General PHP programming knowledge.
  • Eloquent ORM: Understanding how to interact with your database using Eloquent.

Installation and Setup

First, install the Maatwebsite Excel package using Composer:


composer require maatwebsite/excel:~2.1.0

Note: For Laravel versions 6 and above, you should use `maatwebsite/excel:^3.1`. This article focuses on Laravel 5, hence the `~2.1.0` version.

After installation, add the service provider to your `config/app.php` file:


'providers' => [
    // ... other service providers

    Maatwebsite\Excel\ExcelServiceProvider::class,
],

'aliases' => [
    // ... other aliases

    'Excel' => Maatwebsite\Excel\Facades\Excel::class,
],

Finally, publish the configuration file:


php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider"

Core Implementation: Exporting Data

Let's create an example to export user data to an Excel file.


Code Explanation: Exporting Data

The `UsersExport` class implements two interfaces:

  • `FromCollection`: This interface requires a `collection()` method that returns a `\Illuminate\Support\Collection` of data to be exported. In this case, we're fetching all users from the database.
  • `WithHeadings`: This interface requires a `headings()` method that returns an array of strings representing the column headers for the Excel file.

Now, in your controller, you can trigger the export:


Code Explanation: Exporting Data (Controller)

The `export()` method in the `UserController` creates a new instance of the `UsersExport` class and uses the `Excel::download()` method to initiate the download. The first argument is the export class instance, and the second argument is the filename. The extension determines the file type (in this case, `.xlsx`).

Finally, define a route for the `export` method in your `routes/web.php` file:


Route::get('/users/export', 'UserController@export');

Core Implementation: Importing Data

Let's create an example to import user data from an Excel file.


 $row['name'],
            'email'    => $row['email'],
            'password' => bcrypt($row['password']),
        ]);
    }
}

Code Explanation: Importing Data

The `UsersImport` class implements two interfaces:

  • `ToModel`: This interface requires a `model()` method that receives a row of data (as an array) and returns an Eloquent model instance to be saved to the database. We're creating a new `User` instance with data from the row.
  • `WithHeadingRow`: This interface automatically sets the first row as the heading row, so you can access data by column name (e.g., `$row['name']`). Without this, you would need to access data by index (e.g., `$row[0]`).

Now, in your controller, you can handle the import:


file('users'));

        return back()->with('success', 'Users imported successfully!');
    }
}

Code Explanation: Importing Data (Controller)

The `import()` method in the `UserController` receives the uploaded file from the request using `$request->file('users')` (assuming the file input field is named "users"). The `Excel::import()` method imports the data using the `UsersImport` class. A success message is then returned to the user.

To make this work, create a form with a file input:


@csrf

Remember to include the `enctype="multipart/form-data"` attribute in the form to allow file uploads.

Finally, define a route for the `import` method in your `routes/web.php` file:


Route::post('/users/import', 'UserController@import');

Complexity Analysis

The time complexity of exporting data depends largely on the number of records you're exporting. If you're exporting all users (using `User::all()`), the time complexity will be O(n), where n is the number of users in the database. The space complexity is also O(n), as you need to store all user data in memory before writing it to the Excel file.

For importing data, the time complexity is also O(m), where m is the number of rows in the Excel file. For each row, a new User object is created and saved to the database. Saving to the database typically has a complexity that depends on database indexes and the amount of data being written per row. The space complexity is relatively small because only one row is processed at a time.

Alternative Approaches

One alternative approach is to use the native PHPExcel library directly. While this library offers more control over the Excel file generation process, it requires significantly more code to achieve the same functionality as Maatwebsite Excel. It also requires more manual configuration. The trade-off is greater flexibility for increased complexity. Another less performant alternative for large datasets would be to manually parse CSV files using PHP's built-in functions like `fgetcsv()` and insert data into the database accordingly.

Conclusion

Maatwebsite Excel provides a convenient and efficient way to import and export data to Excel and CSV files in Laravel 5 applications. Its simple API allows developers to quickly integrate these features into their projects. By using the `FromCollection`, `ToModel`, `WithHeadings`, and `WithHeadingRow` interfaces, you can easily customize the import and export process to meet your specific needs. Remember to choose the package version that aligns with your Laravel version.