首先,通过composer引入Laravel Excel v2.1库
composer require maatwebsite/excel ~2.1.0
将ServiceProvider添加到提供者数组中 config/app.php
providers数组中添加 Maatwebsite\Excel\ExcelServiceProvider::class, aliasses数组中添加: ‘Excel’ => Maatwebsite\Excel\Facades\Excel::class
这样就可以开始使用Excel了,在类头部use Excel;即可
下面是php示例代码:
public function postLeadExcel(Request $request)
{
$file = $request->file('leadFile');
if($file -> isValid()){
$clientName = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$newName = md5(date('ymdhis').$clientName).".".$extension;
$uploadDir = dirname($_SERVER['SCRIPT_FILENAME']).'/upload/';
$path = $uploadDir.$newName;
$file->move($uploadDir,$newName);
$excel_data = Excel::load($path)->getSheet(0)->toArray();//这就是excel表的数据
// do some thing
}
}
JS:
$("#do_lead").on('click',function(){
var $this = $(this);
$this.prop('disabled', true);
var filepath = $("input[name='leadFile']").val();
var extStart = filepath.lastIndexOf(".");
var ext = filepath.substring(extStart, filepath.length).toUpperCase();
if (ext != ".XLSX" && ext != ".XLS") {
alert("请上传xlsx,xls格式的文件");
}
else {
$("#lead_form").submit();
}
});