1. 下载扩展包: composer require phpoffice/phpspreadsheet
2. html 页面
{include file="public/meta" /}
<article class="page-container">
<form class="form form-horizontal" id="myform" enctype="multipart/form-data">
<div class="row cl" style="margin-bottom: 60px">
<label class="form-label col-xs-4 col-sm-3"><span class="c-red">*</span> 单文件上传:</label>
<div class="formControls col-xs-8 col-sm-9 skin-minimal">
<input class="amend-logo-img-choose-file" type="file" name="file" id="">
</div>
</div>
<hr>
<div class="row cl" style="margin-top: 60px">
<label class="form-label col-xs-4 col-sm-3"><span class="c-red">*</span> 批量文件上传:</label>
<div class="formControls col-xs-8 col-sm-9 skin-minimal">
<input class="" type="file" name="files[]" multiple="multiple" id="file_arr" accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" >
<!-- accept 是限制只能上传 excel 文件-->
</div>
</div>
<div class="row cl">
<div class="col-xs-8 col-sm-9 col-xs-offset-4 col-sm-offset-3">
<button type="button" class="btn btn-success radius sbmit" id="admin-role-save" name="admin-role-save">确定</button>
</div>
</div>
</form>
</article>
{include file="public/footer" /}
<script type="text/javascript" src="__STATIC__/lib/jquery.validation/1.14.0/jquery.validate.js"></script>
<script type="text/javascript" src="__STATIC__/lib/jquery.validation/1.14.0/validate-methods.js"></script>
<script type="text/javascript" src="__STATIC__/lib/jquery.validation/1.14.0/messages_zh.js"></script>
<script type="text/javascript">
$(function(){
$(".sbmit").on('click',function(){
var value = $('#file_arr').val();
if(value.length == 0){
layer.msg('请选择文件');
return false;
}
var index = layer.load(0, {shade: [0.5,'#ADADAD']}); //0代表加载的风格,支持0-2
var form = new FormData($("#myform")[0]);
$.ajax({
url:"/excel-users-login/excel-import-saves",
type:"post",
data:form,
processData:false,
contentType:false,
success:function(data){
if(data.code == '0'){
layer.close(index);
var content =
'<a style="color: #0C0C0C" download="" href='+data.notice_file_txt+'>点击<b style="color:red">下载</b>文本信息</a><br><br>'+
"<p style='color: blue'>一 :这次上传文件总数 : "+data.upload_file_count+"</p> " +
"<p style='color:red'>二:错误文件名称列表 :<br> "+data.error_file_message+"</p> " +
"<p style='color: #0C0C0C'>三:文件上传返回结果信息 :<br> "+data.success_file_message+"</p> ";
layer.confirm(content, {
closeBtn: 0,
btn: ['继续上传','关闭'] //按钮
}, function(){
layer.msg('继续上传', {icon: 1});
}, function(){
//用jquery 删除文件
layer.msg("正在关闭", {time:2000},function(){
parent.location.reload();
});
});
$("#file_arr").val(""); //清空数据
}else{
layer.msg(data.message, {time:1000},function(){layer.closeAll();});
}
}
});
// parent.layer.closeAll();
})
});
$(function(){
$('.amend-logo-img-choose-file').on('change', function() {
var that = $(this);
var file = $(this)[0].files[0];
var formData = new FormData();
formData.append('file', file);
var urls = '/excel-users-login/excel-import-save';
$.ajax({
url: urls,
type: 'POST',
cache: false,
data: formData,
dataType: 'json',
processData: false,
contentType: false,
success: function(data) {
console.log(data);
if(data.code == '0'){
// 验证成功
$(".amend-logo-img-choose-file").val(""); //清空数据
var errorMessage = data.data.error.message;
var identicalMessage = data.data.identical.message;
var successCount = data.data.success.count;
layer.open({
type: 1,
skin: 'layui-layer-demo', //样式类名
closeBtn: 1, //不显示关闭按钮
anim: 2,
shadeClose: true, //开启遮罩关闭
content:
"<p style='color: blue'>该文件总条数 : "+data.data.count+"</p> " +
"<p style='color:red'>1.错误信息 : "+errorMessage+"</p> " +
"<p style='color: #0C0C0C'>2.相同数据 : "+identicalMessage+"</p> " +
"<p style='color:green'>3.成功条数 : "+successCount+"</p>",
});
}else{
layer.msg(data.message, {time:1000},function(){layer.closeAll();});
}
},error:function (data) {
}
});
});
})
</script>
<!--/请在上方写此页面业务相关的脚本-->
</body>
</html>
页面效果:
控制器代码:
<?php
/**
* Created by:
* User: wei
* Date: 2019-10-19
*/
namespace app\admin\controller;
use app\admin\model\UsersLogin;
use app\common\const_arr\ConstArr;
use app\common\err\ErrorCode;
use think\App;
use think\facade\Cache;
use think\Request;
use think\Env;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\Db;
class ExcelUsersLogin extends Base
{
//接收多文件
public function excelImportSaves(Request $request)
{
header("content-type:text/html;charset=utf-8");
//上传excel文件
$files = $request->file("files");
$arr['code'] = 0;
$arr['message'] = "ok";
$err['error_file_name'] = [];
$suc['success_file_name'] = [];
foreach ($files as $k => $file) {
//循环上传文件
$file_name= $file->getInfo()['name'];
$data = file_upload($file);
if(isset($data['data'])){
$fileName = $data['data']['src']; // /uploads/20191022/4882844247d351657450e0f557adb220.xlsx
$data = file_import($fileName);
if (!empty(array_diff($data[0],ConstArr::UsersLogin))) { //注解在下方
$err['error_file_name'][] = $file_name;
}else {
unset($data[0]); //删除第一行的标题
$userLogin = new UsersLogin();
$res = $userLogin->createDataSave($data);
unlink('.'.$fileName);
$file_upload_status['file_name'] = $file_name;
$file_upload_status['success'] = "1.成功条数".$res['success']['count'];
$file_upload_status['error'] = "2.错误信息".$res['error']['message'];
$file_upload_status['identical'] = "3.相同信息".$res['identical']['message'];
$file_upload_status['count'] = "4.总条数".$res['count'];
$suc['success_file_name'][$k]=implode("<br>",$file_upload_status);
}
}
}
//写入文本
$TxtFileName = "User-login.txt";
$this->write_content($TxtFileName,count($files),$err['error_file_name'],$suc['success_file_name']);
$arr['error_file_message'] = implode("<br>",$err['error_file_name']);
$arr['success_file_message'] = implode("<br><hr>",$suc['success_file_name']);
$arr['upload_file_count'] = count($files);
$arr['notice_file_txt'] = "/".$TxtFileName;
//把内容写入文件
return $arr;
}
//记录上传文件的日志文件,
public function write_content($TxtFileName,$file_count,$error_file_name,$success_file_name){
//以读写方式打写指定文件,如果文件不存则创建
if( ($TxtRes=fopen ($TxtFileName,"w+")) === FALSE){
return false;
exit();
}
file_put_contents($TxtFileName,"****文件上传总数*****:".$file_count.PHP_EOL);
foreach($error_file_name as $er => $ev){
if ($er == 0){
$txt = "****错误文件*****";
}else{
$txt = " =》";
}
file_put_contents($TxtFileName, $txt.$ev.PHP_EOL, FILE_APPEND);
}
foreach ($success_file_name as $key=>$val){
$txtArr = explode("<br>",$val);
foreach($txtArr as $kk=>$vv){
if ($kk == 0){
$txt = "****待核对信息文件*****";
}else{
$txt = " =》";
}
$StrContents = file_put_contents($TxtFileName,$txt.$vv.PHP_EOL, FILE_APPEND);
}
}
if(!fwrite ($TxtRes,$StrContents)){ //将信息写入文件
fclose($TxtRes);
return false;
exit();
}
fclose ($TxtRes); //关闭指针
return true;
}
//接收上传的单文件
public function excelImportSave(Request $request)
{
header("content-type:text/html;charset=utf-8");
//上传excel文件
$file = $request->file("file");
if (empty($file)) false;
$data = file_upload($file);
if(isset($data['data'])){
$fileName = $data['data']['src']; // /uploads/20191022/4882844247d351657450e0f557adb220.xlsx
$data = file_import($fileName);
if (!empty(array_diff($data[0],ConstArr::UsersLogin))) {
return ['code'=>ErrorCode::ERRNO['DATAERR'],"message"=>"您上传的Excel 表错误"];
}
unset($data[0]); //删除第一行的标题
$userLogin = new UsersLogin();
$res = $userLogin->createDataSave($data);
unlink('.'.$fileName);
$return_data['code'] = ErrorCode::ERRNO['OK'];
$return_data['message'] = ErrorCode::ERRNO_MAP['OK'];
$return_data['data'] = $res;
return $return_data;
}
}
}
上传返回结果图:
用到的函数方法:
if (!function_exists("file_upload")) {
function file_upload($file) {
if (empty($file)) {
return false;
}
$info = $file->validate(['size'=>15678000,'ext'=>'xlsx,xls'])->move(request()->server("DOCUMENT_ROOT").'/' . 'uploads');
if ($info) {
//getSaveName 20160820/42a79759f284b767dfcb2a0197904287.jpg
//getFilename 42a79759f284b767dfcb2a0197904287.jpg
$picPath = 'uploads/' . str_replace('\\', '/', $info->getSaveName());
if (!$picPath) {
$result = [
'code' => \app\common\err\ErrorCode::ERRNO['UPLOADEERR'],
'msg' => \app\common\err\ErrorCode::ERRNO_MAP['UPLOADEERR'],
];
return $result;
}
$result = [
'code' => \app\common\err\ErrorCode::ERRNO['OK'],
'msg' => '上传成功',
'data' => [
'src' => '/uploads/' . str_replace('\\', '/', $info->getSaveName()),
'title' => ''
]
];
} else {
$result = [
'code' => \app\common\err\ErrorCode::ERRNO['UPLOADEERR'],
'msg' => $file->getError()
];
}
return $result;
}
}
if (!function_exists("file_import")) {
function file_import($fileName){
$path = UPLOAD_PATH .$fileName;
setlocale(LC_ALL, 'zh_CN'); //csv中文乱码
$inputFileType = \PhpOffice\PhpSpreadsheet\IOFactory::identify($path);
$excelReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
if ($inputFileType == 'Csv') { //csv文件读取设置
$excelReader->setInputEncoding('GBK');
$excelReader->setDelimiter(',');
}
$phpexcel = $excelReader->load($path);
$activeSheet = $phpexcel->getActiveSheet();
$sheet = $activeSheet->toArray();
return $sheet;
}
}
//判断文件的内容是否正确
(!empty(array_diff($data[0],ConstArr::UsersLogin)))
//判断接收文件的数据信息是否符合要求
//用户登陆记录日志
const UsersLogin = [
0 =>"broker_id",
1 =>"user_id",
2 =>"ip",
3 =>"login_status",
4 =>"login_type",
5 =>"platform",
6 =>"language",
7 =>"channel",
8 =>"source",
9 =>"login_time",
10 =>"user_agent",
];