首先,我用的项目环境是 lumen 6.0X, php 7.4,下一步lumen是需要安装 phpexcel扩展的,至于步骤,随便百度一下就有很多,只是简单写一下
导出文件 ,对于没有安装的,懒得百度的,可以走一遍这个流程
1、安装 maatwebsite/excel
composer require maatwebsite/excel
2、在bootstrap/app.php中加入 (就是注册)
$app->register(Maatwebsite\Excel\ExcelServiceProvider::class);
3、修改配置获取方式 (在配置里加些东西,理论上加不加应该都可以,会有默认值)
Maatwebsite\Excel\Readers\LaravelExcelReader.php 查找 Config::get 替换为 config
4、走完上面三步,就可以使用了,不过有一个令人头疼的地方就是,镜像是国内的话,会很慢,当初我也是用的国外的代理。
懒得改代码了,就说一下业务场景吧,我们是做考试系统的,里面有excel 导入试题,我们是后端只负责接收excel路径,前端会有专门接口上传文件,我们要做的就是获取前端传过来的 excel,咳咳,有点跑题了,说导入呢
下面贴导入代码:
<?php
namespace App\Http\Controllers\QuesBank;
use App\Http\Controllers\Controller;
use App\Exceptions\CommonapiException;
use Illuminate\Http\Request;
use App\Services\QuesFormatService;
use Maatwebsite\Excel\Facades\Excel;
use PHPUnit\Exception;
class QuesController extends Controller
{
//批量导入试题入库接口
public function quesBathImport(Request $request)
{
try {
$this->validate($request, [
'period_id' => 'required|string',
'ques_url' => 'required|string',
]);
} catch (\Exception $e) {
throw new CommonapiException('param_error');
}
$input = $request->post();
$file = $request->post('ques_url');
//下载到本地
$localName = '/tmp/' . time() . mt_rand(1000, 9999) . '.xls';
$fp_input = fopen($file, 'r');
file_put_contents($localName,