前端部分代码:
/**
* 导入
*/
$('a[type="btn-import"]').bind("click",function(){
$('#importDialog').dialog({
title: '导入文件',
width: 400,
height: 200,
closed: false,
cache: false,
content :'<form action="" id="importForm" >'
+'<div style=" text-align: center;line-height:100px ;">'
+'导入文件: <input class="easyui-filebox" name="file" prompt="选择文件..." buttonText="选择文件" accept="application/vnd.ms-excel" style="width:260px;height:30px" data-options="required:true">'
+'</div></form>',
modal: true,
buttons:[{
text:'导入',
handler:function(){
if (!$("#importForm").form('validate')) return;
var url = 'http://localhost:8082/springmvc2/hello/importExcel.do';
$("#importForm").ajaxSubmit({
timeout:3000000,
type:"post",
url:url,
beforeSend:function(){
$.messager.progress({
title: '提示',
msg: '文件上传中,请稍候……',
text: ''
});
},
complete:function () {
$.messager.progress('close');
},
success:function(json){
if(json.success){
$.messager.alert('温馨提示',json.message);
$('#importDialog').dialog('close');
$('#result_grid').datagrid('load',{});
}else{
$.messager.alert('温馨提示',json.message);
}
},
error: function(XmlHttpRequest, textStatus, errorThrown){
}
});
}
},{
text:'关闭',
handler:function(){
$('#importDialog').dialog('close');
}
}]
});
});
后端代码
@ResponseBody
@RequestMapping("/importExcel")
public Response importExcel(HttpServletResponse response,HttpServletRequest request,@RequestParam("file") MultipartFile file) {
response.setHeader("Access-Control-Allow-Origin", "*");
Response status=new Response(false,"导入成功");
try {
Workbook workbook = importService.getWorkBook(file);
Sheet sheet = null;
List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
Map<String, Object> map=null;
Field[] fields = Person.class.getDeclaredFields();
sheet = workbook.getSheetAt(0); // 获取表
System.out.println(sheet.getLastRowNum());
//忽略标题行
for (int i = 1; i <=sheet.getLastRowNum(); i++) {
Row row= sheet.getRow(i);
if(row!=null){
map=new HashMap<>();
for (int j = 0; j < fields.length; j++) {
if(fields[j].getName().equals("sex")){
map.put(fields[j].getName(), importService.getValue(row.getCell(j)).equals("男")?1:0);
}else if(fields[j].getName().equals("occupation")){
map.put(fields[j].getName(), importService.getValue(row.getCell(j)).equals("教师")?1:2);
}else {
map.put(fields[j].getName(), importService.getValue(row.getCell(j)));
}
}
gridDataService.savePlayer(map);
}
}
status.setSuccess(true);
} catch (IOException e) {
status.setMessage("导入失败");
e.printStackTrace();
}
return status;
}