最近项目有个需求,就是将excel简析后插入mysql数据库中,因此写了一个测试类和一个controller,测试类负责读取excel和简析excel,然后调用发布的接口,传入对象;controller负责将传入对象插入到数据库中。通过httpClient发送请求,详情见:
https://blog.youkuaiyun.com/fz13768884254/article/details/81772187
poi处理过程:
https://blog.youkuaiyun.com/fz13768884254/article/details/81534946
异常发生:
表数据:
简析过程:
map.put("id", cell_0.getNumericCellValue()+"");
调用接口:
public static String post(String url, Map<String, Object> mapParam){
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
String body = null;
try {
StringEntity s = new StringEntity(JsonUtils.toJSONString(mapParam), "UTF-8");
s.setContentEncoding("UTF-8");
s.setContentType("application/json");
post.setEntity(s);
HttpResponse res = client.execute(post);
System.out.println(res.toString());
if(res.getStatusLine().getStatusCode() == HttpStatus.OK.value()){
HttpEntity entity = res.getEntity();
body = entity != null ? EntityUtils.toString(entity) : null;
System.out.println(body);
}
} catch (Exception e) {
e.printStackTrace();
}
return body;
}
调用时一直返回500,检查也没有发现代码问题,后来查看日志发现,controller中接收对象属性hotelId为long类型的,而在poi简析时,数字类型被统一简析为double,即把1->1.0,这样在接口映射时就会报类型转换异常。
异常处理:
方法一:使用NumberFormat 来做格式处理
double d = cell_0.getNumericCellValue();
NumberFormat nf = NumberFormat.getInstance();
String s = nf.format(d);
if (s.indexOf(",") >= 0) {
//这种方法对于自动加".0"的数字可直接解决
//但如果是科学计数法的数字就转换成了带逗号的,例如:12345678912345的科学计数法是1.23457E+13,经过这个格式化后就变成了字符串“12,345,678,912,345”,这也并不是想要的结果,所以要将逗号去掉
s = s.replace(",", "");
}
map.put("hotelId", s);
方法二:在获取该字段时,将其转换为对应的类型字符串
double d = cell_0.getNumericCellValue();
//将double类型转换为对应的字段类型
map.put("id", Double.valueOf(d).longValue()+"");