使用的是一个插件: Support | Laravel Excel
对版本的一些要求
Version | Laravel Version | Php Version | Support |
---|---|---|---|
2.1 | <=5.6 | <=7.0 | Unsupported since 15-5-2018 |
3.0 | ^5.5 | ^7.0 | Unsupported since 31-12-2018 |
3.1 | ^5.8|^6.0|^7.0|^8.0 | ^7.2|^8.0 | New features |
接下来按照步骤安装:
composer require maatwebsite/excel
在config/app.php
中添加
'providers' => [
/*
* Package Service Providers...
*/
Maatwebsite\Excel\ExcelServiceProvider::class,
]
'aliases' => [
...
'Excel' => Maatwebsite\Excel\Facades\Excel::class,
]
然后发布配置后, 会多出一个东西 config/excel.php
php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider" --tag=config
1. 创建一个 import
// UsersImport 这个名字可以自定义, 可以根据你的模型相对应命名
php artisan make:import YaohaoImport
. 这里创建一个控制器,uploadExel 用于文件上传的时候用
public function uploadExel(Request $request)
{
$file = $request->file('file');
if($file -> isValid()) {
$clientName = $file -> getClientOriginalName(); //客户端文件名称..
$tmpName = $file ->getFileName(); //缓存在tmp文件夹中的文件名例如php8933.tmp 这种类型的.
$realPath = $file -> getRealPath(); //这个表示的是缓存在tmp文件夹下的文件的绝对路径
$entension = $file -> getClientOriginalExtension(); //上传文件的后缀.
$mimeTye = $file -> getMimeType(); //也就是该资源的媒体类型
$newName = $newName = md5(date('ymdhis').$clientName).".".$entension; //定义上传文件的新名称
$path = $file -> move('storage\uploads',$newName); //把缓存文件移动到制定文件夹
Excel::import(new YaohaoImport, $path);
return response()->json(['code' => 200, 'msg' => '上传成功']);
}
}
这个是刚才创建的import
<?php
namespace App\Imports;
use App\Parking\Yaohao;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Imports\HeadingRowFormatter;
HeadingRowFormatter::default('none');
class YaohaoImport implements ToModel, WithHeadingRow
{
/**
* @param array $row
*
* @return User|null
*/
public function model(array $row)
{
dump($row);
// Yaohao 是你创建的模型, 数组里是要和数据库字段一样
return new Yaohao([
'number' => $row['number'],
'status' => $row['flag']
]);
}
}
前端上传代码
import { Upload, message } from 'antd';
import { InboxOutlined } from '@ant-design/icons';
const { Dragger } = Upload;
const props = {
name: 'file',
multiple: true,
// action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76', // 这样会跨域
action: '/api/upload',
onChange(info) {
const { status } = info.file;
if (status !== 'uploading') {
console.log(info.file, info.fileList);
}
if (status === 'done') {
message.success(`${info.file.name} file uploaded successfully.`);
} else if (status === 'error') {
message.error(`${info.file.name} file upload failed.`);
}
},
onDrop(e) {
console.log('Dropped files', e.dataTransfer.files);
},
};
ReactDOM.render(
<Dragger {...props}>
<p className="ant-upload-drag-icon">
<InboxOutlined />
</p>
<p className="ant-upload-text">Click or drag file to this area to upload</p>
<p className="ant-upload-hint">
Support for a single or bulk upload. Strictly prohibit from uploading company data or other
band files
</p>
</Dragger>,
mountNode,
);