前台:
1、简洁版:
<!--
文件上传的表单要满足三个条件:
1、表单组件只能用:<input type="file">
2、请求方式只能用 post (post除了可以提交文本数据,还能提交 二进制数据)
3、表单的编码格式只能用:enctype="multipart/form-data"(HTTP协议规定,浏览器每次向后台提交参数,都会对参数进行统一编码)
-->
<div style="margin-top: 100px;margin-left: 600px">
<form action="/importUser" method="post" enctype="multipart/form-data">
<input type="file" name="userFile"><br>
<input type="submit" value="提交">
</form>
</div>
2、模态窗口 + 表单验证
<!--导入按钮-->
<button type="button" class="btn btn-default" data-toggle="modal" data-target="#importUserModal" ><span class="glyphicon glyphicon-import"></span> 上传列表数据(导入)</button>
<!--导入用户 模态窗口-->
<div class="modal fade" id="importUserModal" role="dialog">
<div class="modal-dialog" role="document" style="width: 60%;">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="myModalLabel">导入市场活动</h4>
</div>
<div class="modal-body" style="height: 350px;">
<div style="position: relative;top: 20px; left: 50px;">
请选择要上传的文件:<small style="color: gray;">[仅支持.xls]</small>
</div>
<div style="position: relative;top: 40px; left: 50px;">
<input type="file" id="userFile">
</div>
<div style="position: relative; width: 400px; height: 320px; left: 45% ; top: -40px;" >
<h3>重要提示:</h3>
<ul>
<li>操作仅针对Excel,仅支持后缀名为XLS的文件。</li>
<li>给定文件的第一行将视为字段名。</li>
<li>用户密码以字符串形式录入</li>
<li>请确认您的文件大小不超过5MB。</li>
<li>默认情况下,字符编码是UTF-8 (统一码),请确保您导入的文件使用的是正确的字符编码方式。</li>
<li>建议您在导入真实数据之前用测试文件测试文件导入功能。</li>
</ul>
<ul>
<br><h4><span id="msg" style="color: dodgerblue"></span></h4>
</ul>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
<button id="importUserBtn" type="button" class="btn btn-primary">导入</button>
</div>
</div>
</div>
</div>
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>用户信息统计</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<script type="text/javascript" src="js/jquery-3.4.1.min.js"></script>
<script type="text/javascript" src="js/bootstrap.js"></script>
<script type="text/javascript">
$(function () {
//给导入按钮添加单击事件
$("#importUserBtn").click(function (){
//收集参数
//取得文件后缀名
let userFileName=$("#userFile").val();
let lastIndex=userFileName.lastIndexOf(".")+1;
let suffix=userFileName.substr(lastIndex).toLowerCase();
if (suffix != "xls") {
alert("只支持xls文件");
return;
}
//取得文件本身
let userFile = $("#userFile")[0].files[0];
if (userFile.size > 5 * 1024 * 1024) {
alert("文件大小不能超过5MB");
return;
}
console.log(userFile);
//FormData是ajax提供的接口,可以模拟键值对向后台提交参数;
let formData = new FormData;
formData.append("userFile", userFile);
$("#msg").text("文件导入中......")
$.ajax({
url:'importUser',
data:formData,
processData:false,//设置ajax向后台提交参数之前,是否把参数统一转换成字符串:true--是,false--不是,默认是true
contentType:false,//设置ajax向后台提交参数之前,是否把所有的参数统一按urlencoded编码:true--是,false--不是,默认是true
type:'post',
dataType:'json',
success:function (data) {
if (data.state == "200") {
alert("成功导入" + data.date + "条记录");
$("#importActivityModal").modal("hide");
location.reload();
}else{
alert(data.message);
$("#importActivityModal").modal("show");
}
}
})
})
})
</script>
</head>
后台:
@RequestMapping("/importUser")
public @ResponseBody Object importUser(MultipartFile userFile) throws IOException {
Result result = new Result();
FileInputStream is = null;
try {
String originalFilename = userFile.getOriginalFilename();
//把接收到的excel文件写到磁盘目录中
//路径必须手动创建好,这里放在项目resource下
File file = new File("D:\\.IdeaProjects\\Spring\\csqtest\\src\\main\\resources\\file\\", originalFilename);
//把文件在服务器指定的目录中生成一个相同的文件(相当于文件传入服务器)
userFile.transferTo(file);
//解析excel文件,获取文件数据,并封装在userList中
is = new FileInputStream("D:\\.IdeaProjects\\Spring\\csqtest\\src\\main\\resources\\file\\" + originalFilename);
HSSFWorkbook workbook = new HSSFWorkbook(is);
HSSFSheet sheet = workbook.getSheetAt(0);
HSSFRow row = null;
HSSFCell cell = null;
User user = null;
List<User> userList = new ArrayList<>();
for (int i = 1; i <= sheet.getLastRowNum(); i++) {
row = sheet.getRow(i);
//每遍历一行就是一个User对象
user = new User();
for (int j = 0; j < row.getLastCellNum(); j++) {
cell = row.getCell(j);
//HSSFUtils工具类获取列中数据,将数据放入对象中
String cellValue = HSSFUtils.getCellValueForStr(cell);
if (j == 0) {
user.setUsername(cellValue);
} else if (j == 1) {
user.setPassword(cellValue);
}
}
//每一行中的所有列都封装完成之后,把user保存到list中,每遍历一行封装一个实体类对象
userList.add(user);
}
//调用service方法批量保存用户
int ret = userService.saveCreateUserByList(userList);
result.setState(200);
result.setMessage("导入成功");
result.setDate(ret);
} catch (Exception e) {
e.printStackTrace();
result.setState(1001);
result.setMessage("导入失败");
} finally {
is.close();
}
return result;
}
HSSFUtils.getCellValueForStr()工具类方法
public class HSSFUtils {
/**
* 从指定的HSSFCell对象中获取列的值
*/
public static String getCellValueForStr(HSSFCell cell) {
String ret="";
if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
ret= cell.getNumericCellValue()+"";
} else if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
ret = cell.getStringCellValue();
} else if (cell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN) {
ret = cell.getBooleanCellValue()+"";
} else {
ret = "";
}
return ret;
}
}
批量保存方法
@Override
public int saveCreateUserByList(List<User> list) {
return userMapper.insertUserByList(list);
}
<insert id="insertUserByList" parameterType="com.csq.csqtest.pojo.User">
insert into `user` (username,password) values
<foreach collection="list" item="obj" separator=",">
(#{obj.username},#{obj.password})
</foreach>
</insert>