一.导入过程(基本就是导出的逆向过程)
1.存在一个包含数据的Excel文件
2.将文件作为参数传到服务器
3.服务器解析文件,并将数据封装成实体对象
4.将对象持久化更新到数据库
5.刷新页面导入成功
二.具体代码实现
1.前端
<form id="uploadForm" action="user/upload.do" method="post" enctype="multipart/form-data">
<table>
<tr>
<td>下载模版:</td>
<td><a href="javascript:void(0)" class="easyui-linkbutton" onclick="downloadTemplate()">导入模版</a></td>
</tr>
<tr>
<td>上传文件:</td>
<td><input type="file" name="userUploadFile"></td>
</tr>
</table>
</form>
</div>
2.
@RequestMapping("/upload")
public void upload(@RequestParam(value="userUploadFile",required=true)MultipartFile userUploadFile,HttpServletResponse response)throws Exception{
HSSFWorkbook wb=new HSSFWorkbook(userUploadFile.getInputStream());
HSSFSheet hssfSheet=wb.getSheetAt(0); // 获取第一个Sheet页
if(hssfSheet!=null){
for(int rowNum=1;rowNum<=hssfSheet.getLastRowNum();rowNum++){
HSSFRow hssfRow=hssfSheet.getRow(rowNum);
if(hssfRow==null){
continue;
}
User user=new User();
user.setName(ExcelUtil.formatCell(hssfRow.getCell(0)));
user.setPhone(ExcelUtil.formatCell(hssfRow.getCell(1)));
user.setEmail(ExcelUtil.formatCell(hssfRow.getCell(2)));
user.setQq(ExcelUtil.formatCell(hssfRow.getCell(3)));
Connection con=null;
con=dbUtil.getCon();
userDao.userAdd(con, user);
dbUtil.closeCon(con);
}
}
wb.close();
JSONObject result=new JSONObject();
result.put("success", "true");
ResponseUtil.write(response, result);
}
3.
public int userAdd(Connection con,User user)throws Exception{
String sql="insert into t_user values(null,?,?,?,?)";
PreparedStatement pstmt=con.prepareStatement(sql);
pstmt.setString(1, user.getName());
pstmt.setString(2, user.getPhone());
pstmt.setString(3, user.getEmail());
pstmt.setString(4, user.getQq());
return pstmt.executeUpdate();
}