springmvc 导入excel
测试代码
@RequestMapping(value="/AddImportCooperation") public void AddImportCooperation( ModelMap model, HttpServletResponse response,HttpServletRequest request) throws IOException{ MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; MultipartFile multipartFile = multipartRequest.getFile("file"); String sourceName = multipartFile.getOriginalFilename(); // 原始文件名 String fileType = sourceName.substring(sourceName.lastIndexOf(".")); //System.out.println("上传的文件名为:"+sourceName+"类型为:"+fileType); //System.out.println("项目Id为:"+proId+"项目名称为:"+proName); String base = request.getSession().getServletContext().getRealPath("/WEB-INF/views/upload"); File file = new File(base); if(!file.exists()){ file.mkdirs(); } String path=base + File.separator + sourceName; multipartFile.transferTo(new File(path)); //service.insert("insertAttachment", attach); //上传成功后读取Excel表格里面的数据 System.out.println("路径是"+path); // File read=new File(path); File read=new File(path); Map<String,Cooperation> map=FileUtil.readExcelFile(path); JSONObject json = DWZUtil.returnSuccessJson("导入成功", "", "closeCurrent", "coo/initCooperationList"); DWZUtil.writer(response, json); }
public static Map<String,Cooperation> readExcelFile(String fileName){ //创建对Excel工作薄文件的引用 HashMap<String, Cooperation> map=new HashMap<String, Cooperation>(); try { InputStream is = new FileInputStream(fileName); HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is); // 循环工作表Sheet for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) { HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet); if (hssfSheet == null) { continue; } // 循环行Row for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) { HSSFRow hssfRow = hssfSheet.getRow(rowNum); if (hssfRow == null) { continue; } HSSFCell no = hssfRow.getCell(0); HSSFCell name = hssfRow.getCell(1); HSSFCell age = hssfRow.getCell(2); HSSFCell score = hssfRow.getCell(3); System.out.println(no+""+name+age+score+"测试数据"); // xlsDto.setCj(Float.parseFloat(getValue(cj))); // list.add(xlsDto); } } } catch (Exception e) { e.printStackTrace(); }finally{ } return map; }
参考如下
http://www.cnblogs.com/hongten/archive/2012/02/22/java2poi.html
http://www.cnblogs.com/hongten/p/java_poi_excel_xls_xlsx.html