Bạn có chắc chắn muốn xóa bài viết này không ?
Bạn có chắc chắn muốn xóa bình luận này không ?
Xuất nhập dữ liệu excel/csv bằng maatwebsite/excel (Laravel 8)
Giới thiệu
Xuất tệp Excel Xuất sang cơ sở dữ liệu là một chức năng rất phổ biến trong bất kỳ ứng dụng web nào. Vì vậy, trong bài viết này, tôi sẽ chia sẻ với bạn cách xuất nhập từ DB trong ứng dụng Laravel 8 với ví dụ. Nếu bạn chưa bao giờ xây dựng tệp Excel nhập khẩu vào cơ sở dữ liệu trong ứng dụng Laravel thì đừng lo lắng trong bài viết này, tôi sẽ hướng dẫn cho bạn các bước về cách xuất nhập cơ sở dữ liệu Excel trong ứng dụng Laravel 8.
Laravel có nhiều gói hữu ích để xây dựng chức năng đó. Vì vậy, trong bài viết này, tôi sẽ sử dụng gói MaatWebsite/Excel Laravel để xây dựng chức năng xuất nhập Excel trong ứng dụng Laravel 8 của tôi.
Trong bản demo này, ví dụ đang tạo một bảng 'giao dịch' và tôi đang xuất dữ liệu bảng này vào tệp Excel hoặc CSV và cũng nhập dữ liệu tệp Excel từ cơ sở dữ liệu. Bảng của tôi trông như thế này.
id | name_on_card | card_no | exp_month | exp_year | cvv |
---|---|---|---|---|---|
Trước khi thực hiện chức năng xuất nhập Excel / CSV với trợ giúp của của gói MaatWebsite / Excel. Kiểm tra các yêu cầu sau đây.
PhpSpreadsheet: ^1.6
PHP extension php_zip enabled
PHP extension php_xml enabled
PHP extension php_gd2 enabled
Bước - 1 : Cài Package
Trong bước đầu tiên, chúng ta cần cài đặt gói MaatWebsite / Excel trong ứng dụng Laravel 8 của tôi.
composer require maatwebsite/excel
Sau khi cài đặt gói, hãy mở tệp cấu hình Laravel của bạn nằm ở cấu hình /app.php và thêm các dòng sau. (Nó là tùy chọn cho phiên bản Laravel >= 5.5)
'providers' => [
/*
* Package Service Providers...
*/
Maatwebsite\Excel\ExcelServiceProvider::class,
]
'aliases' => [
...
'Excel' => Maatwebsite\Excel\Facades\Excel::class,
]
Sau đó, sau khi xuất bản nhà cung cấp dịch vụ chạy lệnh sau trong thiết bị đầu cuối của bạn.
php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider" --tag=config
Điều này sẽ tạo một tệp cấu hình mới có tên "config/excel.php". Bạn cũng có thể thay đổi cài đặt mặc định trong tệp này và đặt một tùy chọn mới theo yêu cầu của riêng bạn.
Bước - 2 : Tạo Migrations
Trong bước này, chúng ta cần tạo migrations cho bảng "transactions" trong ứng dụng Laravel 8 của chúng tôi bằng cách sử dụng lệnh sau trong terminal.
php artisan make:migration create_transactions_tbl --create=transactions
Sau đó mở tệp migration đã tạo của bạn vào thư mục "database/migrations" và viết mã sau vào đó.
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateTransactionsTbl extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('transactions', function (Blueprint $table) {
$table->id();
$table->string('name_on_card');
$table->string('card_no');
$table->string('exp_month');
$table->string('exp_year');
$table->string('cvv');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('transactions');
}
}
Sau khi hoàn tất, hãy chạy lệnh "php artisan migrate" trong terminal của bạn để thực hiện di chuyển đã tạo của bạn.
Bước - 3 : Tạo Model
Bây giờ, chúng ta cần tạo model "Transaction.php", chạy lệnh sau.
php artisan make:model Transaction
Sau khi chạy lệnh trên trong thiết bị đầu cuối của bạn thì tệp "Transaction.php" sẽ được tạo trong thư mục "app/Models".
app/Models/Transaction.php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Transaction extends Model
{
use HasFactory;
protected $table = 'transactions';
protected $guarded = array();
}
Bước - 4 : Tạo Route
Bây giờ, hãy tạo tuyến đường sau trong tệp "routes/web.php".
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ExcelController;
// Route for view/blade file.
Route::get('importExportView', [ExcelController::class, 'importExportView'])->name('importExportView');
// Route for export/download tabledata to .csv, .xls or .xlsx
Route::get('exportExcel/{type}', [ExcelController::class, 'exportExcel'])->name('exportExcel');
// Route for import excel data to database.
Route::post('importExcel', [ExcelController::class, 'importExcel'])->name('importExcel');
Bước - 5 : Tạo class Import
MaatWebsite cung cấp một cách để xây dựng lớp Import và chúng ta phải sử dụng nó trong Controller. Vì vậy, nó sẽ là một cách tuyệt vời để tạo một lớp Import mới. Vì vậy, bạn phải chạy lệnh sau và thay đổi mã sau trên tệp đó:
php artisan make:import TransactionsImport --model=Transaction
app/Imports/TransactionsImport.php
namespace App\Imports;
use App\Transaction;
use Maatwebsite\Excel\Concerns\ToModel;
class TransactionsImport implements ToModel
{
/**
* @param array $row
*
* @return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
return new Transaction([
'name_on_card' => $row[0],
'card_no' => $row[1],
'exp_month' => $row[2],
'exp_year' => $row[3],
'cvv' => $row[4],
]);
}
}
Bước - 6 : Tạo class Export
Bây giờ chúng ta cần tạo class Export dùng lệnh sau.
php artisan make:export TransactionsExport --model=Transaction
app/Exports/TransactionsExport.php
namespace App\Exports;
use App\Models\Transaction;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\FromCollection;
class TransactionsExport implements FromCollection, WithHeadings, WithMapping
{
/**
* @return \Illuminate\Support\Collection
*/
public function collection()
{
return Transaction::all();
}
public function headings(): array
{
return [
'Name On Card',
'Card No.',
'Exp Month',
'Exp. Year',
'CVV',
];
}
public function map($transaction): array
{
return [
$transaction->name_on_card,
'XXXXXXXXXXXX' . substr($transaction->card_no, -4, 4),
$transaction->exp_month,
$transaction->exp_year,
$transaction->cvv,
];
}
}
Bước - 7 : Tạo Controller
Bây giờ, hãy tạo tệp "ExcelControll.php" trong thư mục "app\Http\Controllers" bằng cách chạy lệnh sau.
php artisan make:controller ExcelController
app\Http\Controllers\ExcelController.php
namespace App\Http\Controllers;
use App\Models\Transaction;
use Illuminate\Http\Request;
use App\Exports\TransactionsExport;
use App\Imports\TransactionsImport;
class ExcelController extends Controller
{
/**
* @return \Illuminate\Support\Collection
*/
public function importExportView()
{
return view('excel.index');
}
/**
* @return \Illuminate\Support\Collection
*/
public function exportExcel($type)
{
return \Excel::download(new TransactionsExport, 'transactions.'.$type);
}
/**
* @return \Illuminate\Support\Collection
*/
public function importExcel(Request $request)
{
\Excel::import(new TransactionsImport,$request->import_file);
\Session::put('success', 'Your file is imported successfully in database.');
return back();
}
}
Bước - 8 : Tạo View Blade
Sắp xong rồi, chúng ta sẽ tạo một tệp "resources/views/excel/index.blade.php" và viết mã sau vào tệp này.
<!DOCTYPE html>
<html>
<head>
<title>Laravel 8 Excel CSV Import/Export - laravelcode.com</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css" rel="stylesheet">
</head>
<body>
<div class="container" style="margin-top: 5rem;">
@if($message = Session::get('success'))
<div class="alert alert-info alert-dismissible fade in" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<strong>Success!</strong> {{ $message }}
</div>
@endif
{!! Session::forget('success') !!}
<br />
<h2 class="text-title">Import Export Excel/CSV - LaravelCode</h2>
<a href="{{ route('exportExcel', 'xls') }}"><button class="btn btn-success">Download Excel xls</button></a>
<a href="{{ route('exportExcel', 'xlsx') }}"><button class="btn btn-success">Download Excel xlsx</button></a>
<a href="{{ route('exportExcel', 'csv') }}"><button class="btn btn-success">Download CSV</button></a>
<form style="border: 4px solid #a1a1a1;margin-top: 15px;padding: 10px;" action="{{ route('importExcel') }}" class="form-horizontal" method="post" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="file" name="import_file" />
<button class="btn btn-primary">Import File</button>
</form>
</div>
</body>
</html>
Bước cuối
Bây giờ chức năng import-export Excel của bạn được thực hiện. Bây giờ chỉ cần chạy ứng dụng của bạn bằng cách sử dụng lệnh artisan sau.
php artisan serve
Bây giờ, hãy mở URL sau trong trình duyệt.
http://localhost:8000/importExportView
Tôi hy vọng bạn thích bài viết này.
Nguồn:
laravel-excel.com
laravelcode.com




