1. Import
@RequestMapping(value = "importExcelPartInfo.do", method = RequestMethod.POST, headers = { "Accept=application/html" }) public void importExcelPartInfo(HttpServletRequest request,@RequestPart(value = "file") MultipartFile[] uploadfiles,HttpServletResponse response) throws Exception { Map<String, Object> where = DataConvertHelper.getRequestParam(request); UploadResult uploadResult = new UploadResult(); ListResult<Map<String, Object>> result = new ListResult<>(); try { String newPath = DataConvertHelper.getImportPath("mp/iwms/"); String realPath = request.getSession().getServletContext().getRealPath("")+ newPath; File dir = new File(realPath); if (!dir.isDirectory()){ dir.mkdirs(); } String fileformat = "xlsx|xls|"; boolean FileFlag = false; for (MultipartFile multipartFile : uploadfiles) { if (fileformat.indexOf(FilenameUtils.getExtension( . multipartFile.getOriginalFilename ()) the toLowerCase () + "|") < 0) { FileFlag = to true ; BREAK ; } } IF (FileFlag) { uploadResult.setResult ( ". 3" ); uploadResult.setMsg ( "format error, please re-enter"); // Upload file format does returnHtml (uploadResult, Response); return ; } for (a MultipartFile MultipartFile: UploadFiles) { String filename = multipartFile.getOriginalFilename (); File the saveFile = new new File(realPath, filename); multipartFile.transferTo(saveFile); String[] columnNames = {"PART_NO","FORM_PART_NO","PART_NAME_CN","PART_NAME_EN","PART_UNIT" ,"MAN_MODEL", "PART_USE","IS_RETORACTIVITY","IS_ENABLE"}; String fileName = realPath + File.separator + filename; List<Map<String, Object>> dataList = new ExcelHelper<>().readDataFromExcel(fileName, columnNames, 1); if (dataList != null && dataList.size() >0 Result =here for acquiring sql batch cycle, or passing a List//) { partInformationBIZ.importExcelPartInfo(dataList,where); uploadResult.setMsg(result.getMsg()); uploadResult.setResult(result.getResult()); } if(uploadResult.getResult().equals("0")){ JSONObject obj= JSONObject.fromObject(uploadResult.getMsg()); Object ob= obj.get("rows"); List<Map<String,Object>> upload = (List<Map<String,Object>>)ob; // String orgchange=""; String [] columnNames2 = { "PART_NO", "FORM_PART_NO", "PART_NAME_CN", "PART_NAME_EN", "PART_UNIT", "MAN_MODEL", "PART_USE", "IS_RETORACTIVITY", "IS_ENABLE", "IS_TRUE" }; String [] titleNames = { "part number", "Part display number", "Chinese name", "English", "measurement unit", "factory model", "instructions for use", "whether the recovery of plastic parts", "is available." "error" }; // determine whether there is a path, it does not exist create // File dir = new new File (realpath); // iF (dir.isDirectory ()!) // dir.mkdirs (); SheetName String = "information into data correction part" ; String filename2 = realpath the File.separator + + + sheetName ".xlsx"; new ExcelHelper<>().writeDataToExcel(fileName2, sheetName, titleNames, columnNames2, upload); String ip = request.getLocalAddr(); int port = request.getLocalPort(); System.out.println("port:"+port); String downloadUrl = "/" + newPath.replace(File.separator, "/") + "/" + sheetName + ".xlsx"; // downloadUrl = request.getScheme()+"://"+ip+":"+port + downloadUrl; // downloadUrl = downloadUrl; uploadResult.setDownloadUrl (downloadUrl); returnHtml (uploadResult, Response); } } } the catch (Exception E) { logger.error ( "abnormality information:" + e.getMessage (), E); uploadResult. setResult (Globals.FAIL_CODE); uploadResult.setMsg ( "import failed"); // import failed } returnHtml (uploadResult, Response); return ; }
(2) returnHtml () method
private void returnHtml(UploadResult uploadResult, HttpServletResponse response) { try { JSONObject jsonObject = JSONObject.fromObject(uploadResult); String jsonStr = jsonObject.toString(); response.setContentType("text/html;charset=UTF-8"); response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); response.getWriter().write(jsonStr); response.getWriter().flush(); response.getWriter().close(); } catch (Exception e) { e.printStackTrace(); } }
(3) parsing excel file
/ ** * parse Excel file * * @param fileName * Excel file name * @param columnNames * field name as key values of Map * @param startIndex * Data Sheet the start line, index starts at 0 * @return List < map <String, Object >> data * @throws Exception * / public List <map <String, Object >> readDataFromExcel (fileName String, String [] the columnNames, int startIndex) throws Exception { List <map <String, Object >> data = new new ArrayList<Map<String, Object>>(); FileInputStream fis = new FileInputStream(fileName); Workbook workbook = WorkbookFactory.create(fis); Sheet sheet = null; int sheetNum = workbook.getNumberOfSheets(); for (int i = 0; i < sheetNum; i++) { sheet = workbook.getSheetAt(i); data.addAll(readSheet(sheet, columnNames, startIndex)); } return data; }
(4)
* Sheet resolved, returns List <Map <String, Object >> type data * * @param Sheet * Sheet Object * @param the columnNames * field names, as the key value of the Map * @param startIndex * starts reading the data row * @ return List <the Map <String, Object >> data * / Private List <the Map <String, Object >> readSheet (Sheet Sheet, String [] the columnNames, int startIndex) { List <the Map <String, Object >> MAPLIST = new new the ArrayList <the Map <String, Object >> (); Row row = null; int rowNum = sheet.getPhysicalNumberOfRows(); for (int i = startIndex; i < rowNum; i++) { Map<String, Object> map = new HashMap<String, Object>(); row = sheet.getRow(i); for (int j = 0; j < columnNames.length; j++) { map.put(columnNames[j], readCellValue(row.getCell(j))); } mapList.add(map); } return mapList; }
(5)
/ ** * reads the value of the lattice Excel * * @param C * lattice objects in Excel * @return Object Data * / @SuppressWarnings ( "deprecation" ) Private Object readCellValue (the Cell C) { DecimalFormat DF = new new DecimalFormat ( "0" ); IF (C == null ) { return "" ; } the else { Switch (c.getCellType ()) { Case Cell.CELL_TYPE_BLANK: return ""; case Cell.CELL_TYPE_BOOLEAN: return c.getBooleanCellValue(); case Cell.CELL_TYPE_ERROR: return c.getErrorCellValue(); case Cell.CELL_TYPE_FORMULA: return c.getCellFormula(); case Cell.CELL_TYPE_NUMERIC: //String dataFormat = c.getCellStyle().getDataFormatString(); if (DateUtil.isCellDateFormatted(c)) { SimpleDateFormat sdf; //331844 relationship management service function, when importing a file that contains only a cell or an integer of date, format inconsistent import data, otherwise it is 00:00:00 CST. 17 Jan 2016 the Sun a Date c.getDateCellValue D = (); // returned directly to the display. 17 00:00:00 CST 2016 Jan the Sun IF (d.getHours () == 0 && d.getMinutes () == 0 && d.getSeconds () == 0 ) { SDF = new new the SimpleDateFormat ( " the mM-dd-YYYY " ); } the else { SDF = new new the SimpleDateFormat (" the mM-dd-YYYY HH: mm: SS " ); } return sdf.format (D); } the else { return df.format(c.getNumericCellValue()); //数字型 } case Cell.CELL_TYPE_STRING: return c.getStringCellValue(); } return "Unknown Cell Type:" + c.getCellType(); } }
* Get address import file * path = mp / dff / module * @ return * @author oil the a * / public static String getImportPath (String path) { return path + "importDffService" + the File.separator + DateTimeHelper.getCurrentTime ( " yyyyMMdd " ) + the File.separator + StringHelper.GetGUID (); }