Laravel 对 Excel (None)
在 Laravel 项目中处理 Excel 文件是一个常见的需求。介绍如何在 Laravel 中读取和导出 Excel 文件,并提供多种解决方案。
解决方案
Laravel 本身并不直接支持 Excel 操作,但可以通过第三方库来实现。最常用的库是 maatwebsite/excel
,它提供了强大的功能来读取和导出 Excel 文件。如何安装和使用这个库,并提供示例代码。
安装 Maatwebsite/Excel
我们需要通过 Composer 安装 maatwebsite/excel
库。打开终端并运行以下命令:
bash
composer require maatwebsite/excel
安装完成后,需要在 config/app.php
中注册服务提供者和门面:
php
// config/app.php</p>
<p>'providers' => [
// ...
MaatwebsiteExcelExcelServiceProvider::class,
],</p>
<p>'aliases' => [
// ...
'Excel' => MaatwebsiteExcelFacadesExcel::class,
],
读取 Excel 文件
使用 Collection 导入
maatwebsite/excel
提供了多种方式来读取 Excel 文件。最简单的方式是使用 Collection
导入。假设我们有一个 Excel 文件 data.xlsx
,我们可以使用以下代码来读取它:
php
use MaatwebsiteExcelFacadesExcel;
use IlluminateHttpRequest;</p>
<p>public function import(Request $request)
{
$file = $request->file('file');
$data = Excel::toCollection(null, $file);</p>
<pre><code>foreach ($data[0] as $row) {
// 处理每一行数据
echo $row[0] . ' - ' . $row[1] . '<br>';
}
}
使用 Model 导入
如果你希望将 Excel 数据导入到数据库中,可以使用 Model
导入。创建一个导入类:
php
php artisan make:import UsersImport
然后在生成的 UsersImport
类中定义导入逻辑:
php
namespace AppImports;</p>
<p>use AppModelsUser;
use MaatwebsiteExcelConcernsToModel;</p>
<p>class UsersImport implements ToModel
{
public function model(array $row)
{
return new User([
'name' => $row[0],
'email' => $row[1],
'password' => bcrypt($row[2]),
]);
}
}
在控制器中调用导入方法:
php
use AppImportsUsersImport;
use MaatwebsiteExcelFacadesExcel;</p>
<p>public function import(Request $request)
{
$file = $request->file('file');
Excel::import(new UsersImport(), $file);</p>
<pre><code>return redirect()->back()->with('success', '数据导入成功');
}
导出 Excel 文件
使用 Collection 导出
导出 Excel 文件也非常简单。假设我们有一个用户集合,可以使用以下代码将其导出为 Excel 文件:
php
use MaatwebsiteExcelFacadesExcel;
use AppExportsUsersExport;</p>
<p>public function export()
{
return Excel::download(new UsersExport(), 'users.xlsx');
}
创建 UsersExport
类:
php
namespace AppExports;</p>
<p>use AppModelsUser;
use MaatwebsiteExcelConcernsFromCollection;</p>
<p>class UsersExport implements FromCollection
{
public function collection()
{
return User::all();
}
}
使用 View 导出
如果你希望自定义导出的 Excel 文件格式,可以使用 View
导出。创建一个视图文件 resources/views/users/export.blade.php
:
blade</p>
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
@foreach ($users as $user)
<tr>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
</tr>
@endforeach
</tbody>
</table>
<p>
然后在 UsersExport
类中使用 View
导出:
php
namespace AppExports;</p>
<p>use AppModelsUser;
use MaatwebsiteExcelConcernsFromView;
use IlluminateContractsViewView;</p>
<p>class UsersExport implements FromView
{
public function view(): View
{
return view('users.export', [
'users' => User::all()
]);
}
}
通过 maatwebsite/excel
库,我们可以在 Laravel 中轻松地读取和导出 Excel 文件。使用 Collection
和 Model
导入 Excel 文件的方法,以及使用 Collection
和 View
导出 Excel 文件的方法。希望这些示例能帮助你在 Laravel 项目中高效地处理 Excel 文件。
文章来源网络,作者:运维,如若转载,请注明出处:https://shuyeidc.com/wp/68416.html<