How to count row in excel file import in laravel?

Member

by lily , in category: PHP Frameworks , 24 days ago

How to count row in excel file import in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by addison , 23 days ago

@lily 

To count the rows in an Excel file imported in Laravel, you can use the Maatwebsite/Laravel-Excel package. Here's a step-by-step guide on how to achieve this:

  1. Install Maatwebsite/Laravel-Excel package by running the following composer command:
1
composer require maatwebsite/excel


  1. After installing the package, you need to publish the config file by running the command:
1
php artisan vendor:publish --provider="MaatwebsiteExcelExcelServiceProvider"


  1. Now, you can import the Excel file in your Laravel controller. Here is an example of how you can import an Excel file and count the rows:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
use MaatwebsiteExcelFacadesExcel;
use AppImportsYourImportClass;

class YourController extends Controller
{
    public function importExcel()
    {
        $path = storage_path('app/path/to/your/excel_file.xlsx');

        $rows = Excel::toCollection(new YourImportClass, $path)->count();

        return $rows;
    }
}


  1. In this example, replace YourImportClass with the class that extends MaatwebsiteExcelConcernsToCollection and implements its methods. You can define the logic to store the data in this class.
  2. Make sure to change the path to the location of your Excel file.
  3. Call the importExcel method in your route or wherever required to get the count of rows in the Excel file.


By following these steps, you can easily count the rows in an Excel file imported in Laravel using the Maatwebsite/Laravel-Excel package.