1,使用Composer安装依赖
在Laravel项目根目录下使用Composer安装依赖:
composer require maatwebsite/excel ~2.1
ps:一定要加上~2.1!!!因为现在已经更新到3.0版本了,如果你不加的话,会安装最新的3.0版本!等运行时候就会报错,类似下面这样的报错
Symfony Component Debug Exception FatalThrowableError (E_ERROR)Call to undefined method MaatwebsiteExcelExcel::create(),
2,安装后,修改设置
在config/app.php中注册服务提供者到providers数组:
MaatwebsiteExcelExcelServiceProvider::class,
在config/app.php中注册门面到aliases数组:
'Excel' => MaatwebsiteExcelFacadesExcel::class,
执行Artisan命令:
php artisan vendor:publish --provider="MaatwebsiteExcelExcelServiceProvider"
执行成功后会在config目录下生成文件excel.php。
修改生成的excel.php文件
大约是在431行,将'to_ascii' => true,改为
'to_ascii' => false,
<?php
namespace AppHttpControllers;
use AppHttpRequests;
use IlluminateHttpRequest;
use AppHttpControllersController;
use Excel;
class ExcelController extends Controller
{
public function export()
{
$cellData = [
['id','姓名','年龄'],
['10001','张三','19'],
['10002','李四','22'],
['10003','王五','23'],
['10004','赵六','19'],
['10005','猴七','22'],
];
$name = iconv('UTF-8', 'GBK', '成员信息');
Excel::create($name,function($excel) use ($cellData){
$excel->sheet('score', function($sheet) use ($cellData){
$sheet->rows($cellData);
});
})->store('xls')->export('xls');
}
public function import(){
$filePath = 'storage/exports/'.iconv('UTF-8', 'GBK', '成员信息').'.xls';
Excel::load($filePath, function($reader) {
$data = $reader->all(); dump($data);
});
exit;
}
}