全返网站建设,wordpress热门文章,frontpage网页制作,友情贴吧前提#xff1a;项目中需要把EXCEL数据批量导入oracle中两张表中。如是用到了poi技术。分别导入poi-3.11-beta2.jar和poi-ooxml-schemas-3.9.jar这两个包。EXCEL数据如下 第一步#xff1a;修改spring框架配置文件。 springmvc-servlet.xml加上#xff1a; !-- 文件上传… 前提项目中需要把EXCEL数据批量导入oracle中两张表中。如是用到了poi技术。分别导入poi-3.11-beta2.jar和poi-ooxml-schemas-3.9.jar这两个包。EXCEL数据如下 第一步修改spring框架配置文件。 springmvc-servlet.xml加上 !-- 文件上传 -- bean idmultipartResolver classorg.springframework.web.multipart.commons.CommonsMultipartResolver p:defaultEncodingutf-8 / 第一步添加页面jsp。view_user_batchadd.jsp
% page languagejava contentTypetext/html; charsetUTF-8 pageEncodingUTF-8%
% taglib urihttp://java.sun.com/jsp/jstl/core prefixc %
!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN http://www.w3.org/TR/html4/loose.dtd
html
%
String importMsg;
if(request.getSession().getAttribute(msg)!null){
importMsgrequest.getSession().getAttribute(msg).toString();
}
request.getSession().setAttribute(msg, );
%
headtitle批量导入用户/title
meta http-equivContent-Type contenttext/html; charsetUTF-8script typetext/javascript src%request.getContextPath()%/view/js/jquery.js/script
bodyform action%request.getContextPath()%/manager/index/batchimport methodpost enctypemultipart/form-data namebatchAdd οnsubmitreturn check();div stylemargin: 30px;input idexcel_file typefile namefilename acceptxls size50/divinput idexcel_file typefile namefilename size50/input idexcel_button typesubmit value导入Excel//divfont idimportMsg colorred%importMsg%/fontinput typehidden/ /form
/body
script typetext/javascript function check() { var excel_file $(#excel_file).val(); if (excel_file || excel_file.length 0) { alert(请选择文件路径); return false; } else { return true; }
} $(document).ready(function () { var msg; if($(#importMsg).text()!null){ msg$(#importMsg).text(); } if(msg!){ alert(msg); } });
/script
/html第三步填写控制器UserLoginController.Java
/*** 2014-8-30 下午2:52:49* TODO 用户登录 Controller* */
Controller
RequestMapping(/index)
public class UserLoginController {private Log log LogFactory.getLog(UserLoginController.class);Autowiredprivate UserLoginService userLoginService;Autowiredprivate UserInfoService userInfoService;RequestMapping(value /batchimport, method RequestMethod.POST)public ModelAndView batchimport(RequestParam(filename) MultipartFile file,HttpServletRequest request,HttpServletResponse response) throws Exception{log.info(UserLoginController ..batchimport() start);//判断文件名是否为空if(filenull) return null;//获取文件名String namefile.getOriginalFilename();//判断文件大小、即名称long sizefile.getSize();if(namenull || ().equals(name) size0) return null;try {//把文件转换成字节流形式InputStream in file.getInputStream();int iuserLoginService.batchImport(name,file);int juserInfoService.batchImport(name,file);if(i0 j0){String Msg 批量导入EXCEL成功;request.getSession().setAttribute(msg,Msg); }else{String Msg 批量导入EXCEL失败;request.getSession().setAttribute(msg,Msg);}} catch (IOException e) {e.printStackTrace();} return null;}}注我这个Controller的方法里面处理了两个接口实现类。我这里就写一个 第三步实现类UserLoginServiceImpl.java public int batchImport(String name,MultipartFile file) throws Exception {//处理EXCELReadExcel readExcelnew ReadExcel();//获得解析excel方法ListUser userListreadExcel.getExcelInfo(name,file);//把excel信息添加到数据库中ListUserLogin LoginListnew ArrayListUserLogin();for(User user:userList){LoginList.add(user.getUserLogin());}return userLoginDao.saveBatch(LoginList);//添加登录信息}第四步处理EXCEL类ReadExcel.java public class ReadExcel {//总行数private int totalRows 0; //总条数private int totalCells 0; //错误信息接收器private String errorMsg;//构造方法public ReadExcel(){}//得到总行数public int getTotalRows() { return totalRows;} //得到总列数public int getTotalCells() { return totalCells;} public String getErrorInfo() { return errorMsg; } /*** 描述验证EXCEL文件* param filePath* return*/public boolean validateExcel(String filePath){if (filePath null || !(WDWUtil.isExcel2003(filePath) || WDWUtil.isExcel2007(filePath))){ errorMsg 文件名不是excel格式; return false; } return true;}/**描述 :读EXCEL文件* param fielName* return*/public ListUser getExcelInfo(String fileName,MultipartFile Mfile){//把spring文件上传的MultipartFile转换成FileCommonsMultipartFile cf (CommonsMultipartFile)Mfile; DiskFileItem fi (DiskFileItem)cf.getFileItem();File file fi.getStoreLocation(); ListUser userListnew ArrayListUser();InputStream is null; try{//验证文件名是否合格if(!validateExcel(fileName)){return null;}//判断文件时2003版本还是2007版本boolean isExcel2003 true; if(WDWUtil.isExcel2007(fileName)){isExcel2003 false; }is new FileInputStream(file);userListgetExcelInfo(is, isExcel2003); is.close();}catch(Exception e){e.printStackTrace();}finally{if(is !null){try{is.close();}catch(IOException e){is null; e.printStackTrace(); }}}return userList;}/*** 此方法两个参数InputStream是字节流。isExcel2003是excel是2003还是2007版本* param is* param isExcel2003* return* throws IOException*/public ListUser getExcelInfo(InputStream is,boolean isExcel2003){ListUser userListnull;try{/** 根据版本选择创建Workbook的方式 */Workbook wb null;//当excel是2003时if(isExcel2003){wb new HSSFWorkbook(is); }else{wb new XSSFWorkbook(is); }userListreadExcelValue(wb);}catch (IOException e) { e.printStackTrace(); } return userList;}/*** 读取Excel里面的信息* param wb* return*/private ListUser readExcelValue(Workbook wb){ //得到第一个shell Sheet sheetwb.getSheetAt(0);//得到Excel的行数this.totalRowssheet.getPhysicalNumberOfRows();//得到Excel的列数(前提是有行数)if(totalRows1 sheet.getRow(0) ! null){this.totalCellssheet.getRow(0).getPhysicalNumberOfCells();}ListUser userListnew ArrayListUser();User user; //用户bean组成UserInfoUserLoginUserInfo userInfo; //用户基本信息beanUserLogin userLogin; //用户登录bean//循环Excel行数,从第二行开始。标题不入库for(int r1;rtotalRows;r){Row row sheet.getRow(r);if (row null) continue;usernew User();userInfonew UserInfo();userLoginnew UserLogin();//循环Excel的列for(int c 0; c this.totalCells; c){ Cell cell row.getCell(c); if (null ! cell) {//第一列if(c0){//获得第一列用户名放到到用户基本信息bean中。userInfo.setUserName(cell.getStringCellValue());}//获得第二列手机号放到到用户登录bean中。作为登录账号及密码else if(c1){/*** 处理使用POI读excel文件当遇到特殊格式的字串比如“13612345678”等等* 这样的本来是一个字符串但是POI在读的时候总是以数值型识别由此这样的电话号码读出来后总是1.3XXXE4*/DecimalFormat df new DecimalFormat(#);String cellValuedf.format(cell.getNumericCellValue());userLogin.setAccount(cellValue);userLogin.setPwd(cellValue);}//第三列目前不入库只是展示即可//第四列用户地址,放到到用户基本信息bean中。else if(c3){userInfo.setCompanyAdd(cell.getStringCellValue());}}}//添加其他值入库时需要userLogin.setUserId(Utils.getzId());//存放用户IDuserLogin.setInsertTime(Utils.getshortDate());//注册时间userLogin.setUserRole(2); //默认导入的用户都为供应商级别userInfo.setUserInfoid(Utils.getzId());//存放用户IDuserInfo.setUserId(userLogin.getUserId());//基本信息的用户IDuser.setUserInfo(userInfo);user.setUserLogin(userLogin);userList.add(user);}return userList;}
}
/** * 描述工具类 * 检验是否是EXCEL文件*/
class WDWUtil
{ // 描述是否是2003的excel返回true是2003 public static boolean isExcel2003(String filePath) { return filePath.matches(^.\\.(?i)(xls)$); } //描述是否是2007的excel返回true是2007 public static boolean isExcel2007(String filePath) { return filePath.matches(^.\\.(?i)(xlsx)$); }
}