【Laravel】使用 Laravel Excel 實現 Excel/CSV 文件導入導出功能


一、安裝配置

使用Composer安裝依賴:

composer require maatwebsite/excel

發布配置(可選):

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

配置config/app.phpprovidersaliases(可選):

'providers' => [
    /*
     * Package Service Providers...
     */
    Maatwebsite\Excel\ExcelServiceProvider::class,
]
'aliases' => [
    //...
    'Excel' => Maatwebsite\Excel\Facades\Excel::class,
]

二、使用方式

創建導出和導入類:

php artisan make:export UsersExport --model=App\\User
php artisan make:import UsersImport --model=App\\User

(一)數據導出

編寫導出類實現相應接口:https://laravel-excel.maatwebsite.nl/3.1/exports/concerns.html

控制器代碼:

public function export()
{
    return Excel::download(new UsersExport, 'users.xlsx');
}

(二)數據導入

編寫導入類實現相應接口:https://laravel-excel.maatwebsite.nl/3.1/imports/concerns.html

控制器代碼:

public function import()
{
    return Excel::import(new UsersImport, 'users.xlsx');
}

數據導入注意事項:

Excel::import($import, $filePath, $disk = null, $readerType = null)方法注意事項

①方式一:可以不用將excel文件上傳到磁盤,方法第二個參數設置為上傳文件對象的實例,例如:

Excel::import(new UsersImport, $request->file('excel'));

②方式二:將excel文件上傳到磁盤,第二個參數設置為相對於磁盤的相對路徑,第三個參數需設置為磁盤名。如果不設置磁盤名會采用默認磁盤。例如:

  文件地址為:. . ./storage/app/public/excel/user.xlsx (軟鏈接地址為:/public/storage/excel/user.xlsx)==>>$filePath應該設置為:excel\user.xlsx

 Excel::import(new UsersImport, $fileName,'public');

數據導入注意事項:

  ①默認情況下,直接導入數據庫會將表格所有數據導入(包括第一行表頭),如果不需要第一行數據,應該手動處理,或者導入類實現Maatwebsite\Excel\Concerns\WithHeadingRow接口來把第一行作為標題行。

  ②使用模型進行添加數據不要忘了給模型設置$fillable或$guarded屬性。

三、參考文檔:

依賴庫地址:https://packagist.org/packages/maatwebsite/excel

官方文檔:https://laravel-excel.maatwebsite.nl/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM