前提:項目中需要把EXCEL數據批量導入oracle中兩張表中。如是用到了poi技術。分別導入poi-3.11-beta2.jar和poi-ooxml-schemas-3.9.jar這兩個包。EXCEL數據如下
第一步:修改spring框架配置文件。?springmvc-servlet.xml加上:
?<!-- 文件上傳 -->
?????? <bean id="multipartResolver"?? class="org.springframework.web.multipart.commons.CommonsMultipartResolver"? p:defaultEncoding="utf-8" />??
第一步:添加頁面jsp。view_user_batchadd.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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){
importMsg=request.getSession().getAttribute("msg").toString();
}
request.getSession().setAttribute("msg", "");
%>
<head><title>批量導入用戶</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><script type="text/javascript" src="<%=request.getContextPath()%>/view/js/jquery.js"></script>
<body><form action="<%=request.getContextPath()%>/manager/index/batchimport" method="post" enctype="multipart/form-data" name="batchAdd" οnsubmit="return check();"><div style="margin: 30px;"><input id="excel_file" type="file" name="filename" accept="xls" size="50"/><div><input id="excel_file" type="file" name="filename" size="50"/><input id="excel_button" type="submit" value="導入Excel"/></div><font id="importMsg" color="red"><%=importMsg%></font><input type="hidden"/> </form>
</body>
<script type="text/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(file==null) return null;//獲取文件名String name=file.getOriginalFilename();//判斷文件大小、即名稱long size=file.getSize();if(name==null || ("").equals(name) && size==0) return null;try {//把文件轉換成字節流形式InputStream in = file.getInputStream();int i=userLoginService.batchImport(name,file);int j=userInfoService.batchImport(name,file);if(i>0 && j>0){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 readExcel=new ReadExcel();//獲得解析excel方法List<User> userList=readExcel.getExcelInfo(name,file);//把excel信息添加到數據庫中List<UserLogin> LoginList=new ArrayList<UserLogin>();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 List<User> getExcelInfo(String fileName,MultipartFile Mfile){//把spring文件上傳的MultipartFile轉換成FileCommonsMultipartFile cf= (CommonsMultipartFile)Mfile; DiskFileItem fi = (DiskFileItem)cf.getFileItem();File file = fi.getStoreLocation(); List<User> userList=new ArrayList<User>();InputStream is = null; try{//驗證文件名是否合格if(!validateExcel(fileName)){return null;}//判斷文件時2003版本還是2007版本boolean isExcel2003 = true; if(WDWUtil.isExcel2007(fileName)){isExcel2003 = false; }is = new FileInputStream(file);userList=getExcelInfo(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 List<User> getExcelInfo(InputStream is,boolean isExcel2003){List<User> userList=null;try{/** 根據版本選擇創建Workbook的方式 */Workbook wb = null;//當excel是2003時if(isExcel2003){wb = new HSSFWorkbook(is); }else{wb = new XSSFWorkbook(is); }userList=readExcelValue(wb);}catch (IOException e) { e.printStackTrace(); } return userList;}/*** 讀取Excel里面的信息* @param wb* @return*/private List<User> readExcelValue(Workbook wb){ //得到第一個shell Sheet sheet=wb.getSheetAt(0);//得到Excel的行數this.totalRows=sheet.getPhysicalNumberOfRows();//得到Excel的列數(前提是有行數)if(totalRows>=1 && sheet.getRow(0) != null){this.totalCells=sheet.getRow(0).getPhysicalNumberOfCells();}List<User> userList=new ArrayList<User>();User user; //用戶bean(組成:UserInfo+UserLogin)UserInfo userInfo; //用戶基本信息beanUserLogin userLogin; //用戶登錄bean//循環Excel行數,從第二行開始。標題不入庫for(int r=1;r<totalRows;r++){Row row = sheet.getRow(r);if (row == null) continue;user=new User();userInfo=new UserInfo();userLogin=new UserLogin();//循環Excel的列for(int c = 0; c <this.totalCells; c++){ Cell cell = row.getCell(c); if (null != cell) {//第一列if(c==0){//獲得第一列<用戶名>,放到到用戶基本信息bean中。userInfo.setUserName(cell.getStringCellValue());}//獲得第二列<手機號>,放到到用戶登錄bean中。作為登錄賬號及密碼else if(c==1){/*** 處理:使用POI讀excel文件,當遇到特殊格式的字串,比如“13612345678”,等等,* 這樣的本來是一個字符串,但是POI在讀的時候總是以數值型識別,由此,這樣的電話號碼讀出來后總是1.3XXX+E4*/DecimalFormat df = new DecimalFormat("#");String cellValue=df.format(cell.getNumericCellValue());userLogin.setAccount(cellValue);userLogin.setPwd(cellValue);}//第三列目前不入庫,只是展示即可//第四列<用戶地址>,放到到用戶基本信息bean中。else if(c==3){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)$"); }
}