今天给大家介绍一下再java中怎么获取excel表格中的数据
前端上传文件:
<div class="tabCon">
<div style="text-align: center;margin-top: 20%">
<span class="btn-upload form-group">
<label id="error"></label>
<input class="input-text upload-url" type="text" name="excel_file_name" readonly="">
<a href="javascript:void();" class="btn btn-primary upload-btn"><i class="Hui-iconfont"></i> 选择Excel</a>
<input type="file" multiple="" name="excel_file" id="excel_file" class="input-file">
</span>
<input style="margin-left: 10px" class="btn btn-primary" type="submit" value=" 一键导入 " />
</div>
</div>
js:
var formData = new FormData();
formData.append('excel_file', $('#excel_file')[0].files[0]);
//ajax提交保存
$.ajax({
type : 'POST',
url : '<%=path%>/system.mdo?method=importNetHard',
datatype : "text",
data : formData,
processData : false, //必须,配合formdata
contentType : false,
success : function(data) {
if (data.statusCode==200) {//导入成功
} else {
}
}
});
java中:
@RequestMapping(params = "method=importNetHard", method = RequestMethod.POST)
public @ResponseBody Map<String, Object> importNetHard(HttpServletRequest request) throws Exception {
/* 返回的json数据 */
Map<String, Object> jsonMap = new HashMap<>();
// 1.获取参数
MultipartHttpServletRequest fileRequest = (MultipartHttpServletRequest) request;
MultipartFile file = fileRequest.getFile("excel_file");
// 2. 验证
if (file == null || file.getSize() == 0)
return json4Map(jsonMap, null, "文件为空,导入失败!", STATUSCODE_FAILED_BADINPUT_PARAM);
// 3.操作
if (systemService.importExcel2DB(file))
return json4Map(jsonMap, null, "文件已导入!", STATUSCODE_SUCCESS);
return json4Map(jsonMap, null, "导入失败!", STATUSCODE_FAILED);
}
@Override
public boolean importExcel2DB(MultipartFile file) throws Exception {
// 1.取得上传目录父路径
String baseDir = UploadUtil.class.getClassLoader().getResource("/").getPath() + "tmp/";
// 2.重命名上传文件
String fileName = "excel_" + DateTime.now().toString("yyyyMMddHHmmssSSS")
+ file.getOriginalFilename().replaceAll("^[\\s\\S]+(\\.\\w+)", "$1");
// 3.建立文件路径
File _baseDir = new File(baseDir);
if (!_baseDir.exists() && !_baseDir.mkdir())
return false;
// 4.转储为文件
File localFile = new File(baseDir + fileName);
file.transferTo(localFile);
return importExcel2DB4T(localFile);
}
@Override
public boolean importExcel2DB4T(File file) throws Exception {
// 1.将file文件内容转为list集合
List<List<Object>> list = ExcelUtil.importExcel2Collection(file, 0);
// 2.循环生成对象,并存入数据库
Nethard nethard = new Nethard();
int count = 0;
int size = list.size();
StringBuilder error = new StringBuilder("excel导入网卡到数据库时发生异常,出现重复的数据![");
for (int i = 1; i < size; i++) {
List<Object> tmp = list.get(i);
String phone = (String) tmp.get(0);
nethard.setNhPhone(phone);
nethard.setNhNote((String) tmp.get(1));
nethard.setNhImsi((String) tmp.get(2));
nethard.setNhIccid((String) tmp.get(3));
nethard.setNhUserstate("待激活".equals(tmp.get(6)) ? 0 : 1);
nethard.setNhWorkstate("离线".equals(tmp.get(7)) ? 0 : 1);
nethard.setNhUsemb(Double.parseDouble((String) tmp.get(8)));
nethard.setNhUsemsg(Integer.parseInt((String) tmp.get(9)));
nethard.setNhCreatedate((String) tmp.get(10));
nethard.setNhActivedate((String) tmp.get(11));
nethard.setNhIsmsg("是".equals(tmp.get(12)) ? 1 : 0);
nethard.setNhIsgprs("是".equals(tmp.get(13)) ? 1 : 0);
if (nethardMapper.isExists(nethard.getNhPhone())) {
count++;
error.append("Phone:" + phone + ",");
continue;
}
count += nethardMapper.insertSelective(nethard);
}
if (error.toString().indexOf("Phone") > -1) // 如果存在重复数据,打印
logger.error(error.toString().replaceAll("([\\s\\S]+),", "$1]"));
// 删除上传文件
file.delete();
return count == size - 1;
}
如有需要可以加我Q群【308742428】大家一起讨论技术。
后面会不定时为大家更新文章,敬请期待。