依赖安装
composer require maatwebsite/excel
安装完成后,你需要在 config/app.php
文件中的 providers
数组中添加以下行:
Maatwebsite\Excel\ExcelServiceProvider::class,
然后,在 config/app.php
文件中的 aliases
数组中添加以下行:
'Excel' => Maatwebsite\Excel\Facades\Excel::class,
接下来,你可以使用以下代码来生成 Excel 文件:
use Maatwebsite\Excel\Facades\Excel;
Excel::create('filename', function($excel) {
$excel->sheet('Sheetname', function($sheet) {
$sheet->setCellValue('A1', 'Hello');
$sheet->setCellValue('B1', 'World');
});
})->export('xlsx');
use Maatwebsite\Excel\Facades\Excel;
$data = [
['John', 'Doe', 'john@example.com'],
['Jane', 'Smith', 'jane@example.com'],
['Mike', 'Johnson', 'mike@example.com'],
];
Excel::create('filename', function($excel) use ($data) {
$excel->sheet('Sheetname', function($sheet) use ($data) {
foreach ($data as $rowIndex => $rowData) {
$row = $rowIndex + 1;
$sheet->setCellValue('A' . $row, $rowData[0]);
$sheet->setCellValue('B' . $row, $rowData[1]);
$sheet->setCellValue('C' . $row, $rowData[2]);
}
});
})->export('xlsx');