因为以前项目中有用到过Excel导入,所以整理了一下,这是一个导入Excel数据到数据库的方法
注意:需要导入poi jar包
代码清单
/** * Excel 导入 * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward inpexcel(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { UsForm uf = (UsForm)form; String url = uf.getUrl();//获取Excel文件路径 int input = 0; String name = null; String age = null; String sex = null; String likes = null; InputStream inputstream; try { inputstream = new FileInputStream(url); HSSFWorkbook hssfworkbook = new HSSFWorkbook(inputstream); HSSFSheet hssfsheet = hssfworkbook.getSheetAt(0);//第一个工作表 HSSFRow hssfrow = hssfsheet.getRow(0);//第一行 //遍历该表格中所有的工作表,i表示工作表的数量 getNumberOfSheets表示工作表的总数 for (int i = 0; i < hssfworkbook.getNumberOfSheets(); i++) { hssfsheet = hssfworkbook.getSheetAt(i); //遍历该行所有的行,j表示行数 getPhysicalNumberOfRows行的总数 for (int j = 1; j < hssfsheet.getPhysicalNumberOfRows(); j++) { hssfrow = hssfsheet.getRow(j); //判断是否还存在需要导入的数据 if (hssfrow == null) { System.out.println("这里已没有数据,在第"+i+"列,第"+j+"行"); break; } /**将EXCEL中的第 j 行,第一列的值插入到name*/ if (hssfrow.getCell((short) 0) == null) { name = ""; } else if (hssfrow.getCell((short) 0).getCellType() == 0) { name = new Double(hssfrow.getCell((short) 0).getNumericCellValue()).toString(); } //如果EXCEL表格中的数据类型为字符串型 else { name = hssfrow.getCell((short) 0).getStringCellValue().trim(); } /**将EXCEL中的第 j 行,第二列的值插入到sex*/ if(hssfrow.getCell((short) 1) == null){ sex = ""; } else if(hssfrow.getCell((short) 1).getCellType() == 0) { sex = new Double(hssfrow.getCell((short) 1).getNumericCellValue()).toString(); } //如果EXCEL表格中的数据类型为字符串型 else { sex = hssfrow.getCell((short) 1).getStringCellValue().trim(); } /**将EXCEL中的第 j 行,第三列的值插入到age*/ if(hssfrow.getCell((short) 2) == null){ age = ""; } else if(hssfrow.getCell((short) 2).getCellType() == 0) { age = new Double(hssfrow.getCell((short) 2).getNumericCellValue()).toString(); } //如果EXCEL表格中的数据类型为字符串型 else { age = hssfrow.getCell((short) 2).getStringCellValue().trim(); } /**将EXCEL中的第 j 行,第三列的值插入到likes*/ if(hssfrow.getCell((short) 3) == null){ likes = ""; } else if(hssfrow.getCell((short) 3).getCellType() == 0) { likes = new Double(hssfrow.getCell((short) 3).getNumericCellValue()).toString(); } //如果EXCEL表格中的数据类型为字符串型 else { likes = hssfrow.getCell((short) 3).getStringCellValue().trim(); } name = name.trim(); sex = sex.toUpperCase();//将取到的值赋给uf对象存储 uf.getUf().setName(name); uf.getUf().setAge(age); uf.getUf().setSex(sex); uf.getUf().setLikes(likes); Session session = HibernateSessionFactory.getSession();//hibernate 存储 Transaction tx = session.beginTransaction(); session.save(uf.getUf()); tx.commit(); session.close(); //导入成功加1 input++; } } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return mapping.findForward("suc"); }