1. 程式人生 > >在 Laravel 使用擴充套件包maatwebsite/excel 實現 Excel/CSV 檔案匯入匯出功能

在 Laravel 使用擴充套件包maatwebsite/excel 實現 Excel/CSV 檔案匯入匯出功能

一、安裝
1、composer require maatwebsite/excel ~2.0.0
2、在專案下composer.json中require裡新增"maatwebsite/excel":"~2.0.0",並執行composer update 載入該包
二、配置
1、在config/app.php中註冊服務提供者到providers陣列:Maatwebsite\Excel\ExcelServiceProvider::class,
2、在config/app.php中註冊門面到aliases陣列  'Excel' => Maatwebsite\Excel\Facades\Excel::class,
3、更多配置php artisan vendor:publish;執行成功會在config目錄下生成一個配置檔案excel.php。
三、路由
Route::get('excel/export','
[email protected]
');
Route::get('excel/import','[email protected]');
四、新建控制器
1、匯出
<?php


namespace App\Http\Controllers;


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


use Excel;


class ExcelController extends Controller
{
//Excel檔案匯出功能 By Laravel學院
public function export(){
$cellData = [
['學號','姓名','成績'],
['10001','AAAAA','99'],
['10002','BBBBB','92'],
['10003','CCCCC','95'],
['10004','DDDDD','89'],
['10005','EEEEE','96'],
];
Excel::create('學生成績',function($excel) use ($cellData){
$excel->sheet('score', function($sheet) use ($cellData){
$sheet->rows($cellData);
});
})->export('xls');
}
}
?>
我們在瀏覽器中訪問http://laravel.app:8000/excel/export,會匯出一個名為學生成績.xls的Excel檔案:
注意:1、如果你要匯出csv或者xlsx檔案,只需將export方法中的引數改成csv或xlsx即可。
 2、可以使用store方法把檔案儲存在伺服器上
 Excel::create('學生成績',function($excel) use ($cellData){
$excel->sheet('score', function($sheet) use ($cellData){
$sheet->rows($cellData);
});
  })->store('xls')->export('xls');
  檔案會預設儲存在storage/exports目錄下,如果檔案有亂碼可以用iconv('UTF-8', 'GBK', '學生成績')來處理
2、匯入
//Excel檔案匯入功能 By Laravel學院
public function import(){
$filePath = 'storage/exports/'.iconv('UTF-8', 'GBK', '學生成績').'.xls';
Excel::load($filePath, function($reader) {
$data = $reader->all();
dd($data);
});
}



使用瀏覽器訪問:訪問http://laravel.app:8000/excel/import。




該文為整理文件,如有侵權,聯絡作者刪除。源文請參考:http://laravelacademy.org/post/2024.html