Java导入csv文件以及解决中文乱码

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/k469785635/article/details/76020802

第一行通过MultipartFile得到java.util.Scanner对象的时候,要加上GBK这个参数,否则,当csv文件中存在中文时,可能会出现中文乱码的情况。

userDelimiter("\\A")直接这样写就行,具体为什么这样写目前还没有研究。

// file就是MultipartFile ,controller中从前台获取
Scanner s = new Scanner(file.getInputStream(), "GBK").useDelimiter("\\A");
String result = s.hasNext() ? s.next() : "";
List<User> userList = new ArrayList<User>();
try {
	List<Map<String, Object>> data = JsonUtil.readObjectsFromCsv(result);
	JSONArray json = JsonUtil.listOfMapToJsonArray(data);
	JSONObject jsonObj = null;
	Date date = null;
	SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
	for (int i = 0; i < json.length(); i++) {
		User user = new User();
		jsonObj = json.getJSONObject(i);
		String id = jsonObj.getString("ID");
		String name = jsonObj.getString("name");
		String age = jsonObj.getString("age");
		String telephone = jsonObj.getString("telephone");
		String sex = limitAndCurrency.replaceAll("sex");
		user.setId(id);
		user.setName(name);
		user.setAge(age);
		user.setTelephone(telephone);
		user.setSex(sex);
		//设置一些默认属性
		user.setType("1");
		user.setIsClosed("1");
                userList.add(user);
	}
} catch (Exception e) {
	e.printStackTrace();
}
return userList;

通过上面代码得到用户集合userList,然后就可以通过批量新增的方法插入到数据库中了。

MyBatis中,以下代码可以实现数据不存在就新增,存在就更新(根据主键判断):

该方法只适用于MySQL数据库!!!

<insert id="batchInsert" parameterType="java.util.List">
  	insert into user(<include refid="Base_Column_List"/>)
  	values 
  	<foreach collection="list" item="item" index="index" separator=",">
  		(
  			#{item.id,jdbcType=VARCHAR},
  			#{item.name,jdbcType=VARCHAR},
  			#{item.age,jdbcType=VARCHAR},
  			#{item.telephone,jdbcType=VARCHAR},
  			#{item.sex,jdbcType=VARCHAR},
  			#{item.type,jdbcType=VARCHAR},
  			#{item.isClosed,jdbcType=VARCHAR}
  		)
  	</foreach>
  	ON DUPLICATE KEY UPDATE 
  	name = VALUES(name),
  	age = VALUES(age),
  	telephone = VALUES(telephone),
  	sex = VALUES(sex),
  	type = VALUES(type),
  	is_closed = VALUES(is_closed)
</insert>

进行测试,导入成功!

猜你喜欢

转载自blog.csdn.net/k469785635/article/details/76020802