导入、导出功能

导入功能
1.使用ExcelUtil.java工具类,核心代码:

  1 public Map<String,Object> importExcelForRslt(File file, String... pattern)
  2     {
  3         Map<String,Object> importRslt = new HashMap<String,Object>();
  4         importRslt.put("status", "OK");
  5         int countRow = 0;    //
  6         int countCloum = 0;    //
  7         String outMessage = "";
  8         Collection<T> dist = new ArrayList<T>();
  9         /**
 10          * 类反射得到调用方法
 11          */
 12         try{
 13             // 得到目标目标类的所有的字段列表
 14             Field[] fields = clazz.getDeclaredFields();
 15             // 将所有标有Annotation的字段,也就是允许导入数据的字段,放入到一个map中
 16             Map<String, Method> fieldMap = new HashMap<String, Method>();
 17             // 循环读取所有字段
 18             for (Field field : fields) {
 19                 // 得到单个字段上的Annotation
 20                 ExcelAnotation excelAnnotation = field.getAnnotation(ExcelAnotation.class);
 21                 // 如果标识了Annotationd
 22                 if (excelAnnotation != null) {
 23                     String fieldName = field.getName();
 24                     // 构造设置了Annotation的字段的Setter方法
 25                     String setMethodName = "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
 26                     // 构造调用的method
 27                     Method setMethod = clazz.getMethod(setMethodName, new Class[] { field.getType() });
 28                     // 将这个method以Annotaion的名字为key来存入
 29                     fieldMap.put(excelAnnotation.exportName(), setMethod);
 30                 }
 31 
 32             }
 33             /**
 34              * excel的解析开始
 35              */
 36             // 将传入的File构造为FileInputStream;
 37             InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
 38             // 得到工作表
 39             Workbook book = createWorkbook(inputStream);
 40             int numberOfSheets = book.getNumberOfSheets();
 41             for (int iter = 0; iter < numberOfSheets; iter++) {
 42                 Sheet sheet = book.getSheetAt(iter);
 43                 // 得到第一面的所有行
 44                 Iterator<Row> row = sheet.rowIterator();
 45                 /**
 46                  * 标题解析
 47                  */
 48                 // 得到第一行,也就是标题行
 49                 while (row.hasNext()) {
 50                     Row titleRow = row.next();
 51 
 52                     // 得到第一行的所有列
 53                     Iterator<Cell> cellTitle = titleRow.cellIterator();
 54                     // 将标题的文字内容放入到一个map中
 55                     Map<Integer, String> titleMap = new HashMap<Integer, String>();
 56                     // 从标题第一列开始
 57                     int i = 0;
 58                     // 循环标题所有的列
 59                     while (cellTitle.hasNext()) {
 60                         Cell cell = (Cell) cellTitle.next();
 61                         String value = cell.getStringCellValue();
 62                         titleMap.put(i, value);
 63                         i++;
 64                     }
 65 
 66                     /**
 67                      * 解析内容行
 68                      */
 69                     while (row.hasNext()) {
 70                         countRow++;
 71                         countCloum++;
 72                         
 73                         // 标题下的第一行
 74                         Row rown = row.next();
 75                         // 行的所有列
 76                         T tObject = clazz.newInstance();
 77                         int col = 0;
 78                         try {
 79                             for (int n = 0; n < rown.getLastCellNum(); n++) {
 80                                 Cell cell = rown.getCell(n, Row.CREATE_NULL_AS_BLANK);
 81                                 String titleString = titleMap.get(col++);
 82                                 // 如果这一列的标题和类中的某一列的Annotation相同,那么则调用此类的的set方法,进行设值
 83                                 if (fieldMap.containsKey(titleString)) {
 84                                     Method setMethod = fieldMap.get(titleString);
 85                                     // 得到setter方法的参数
 86                                     Type[] types = setMethod.getGenericParameterTypes();
 87                                     // 只要一个参数
 88                                     String xclass = String.valueOf(types[0]);
 89                                     // 判断参数类型
 90                                     if ("class java.lang.String".equals(xclass)) {
 91                                         cell.setCellType(Cell.CELL_TYPE_STRING);
 92                                         setMethod.invoke(tObject, cell.getStringCellValue());
 93                                     } else if ("class java.util.Date".equals(xclass)) {
 94                                         setMethod.invoke(tObject, cell.getDateCellValue());
 95                                     } else if ("class java.lang.Boolean".equals(xclass)) {
 96                                         Boolean boolName = true;
 97                                         if ("否".equals(cell.getStringCellValue())) {
 98                                             boolName = false;
 99                                         }
100                                         setMethod.invoke(tObject, boolName);
101                                     } else if ("class java.lang.Integer".equals(xclass)) {
102                                         setMethod.invoke(tObject, new Integer(String.valueOf((int) cell.getNumericCellValue())));
103                                     } else if ("class java.lang.Long".equals(xclass)) {
104                                         setMethod.invoke(tObject, new Long(cell.getStringCellValue()));
105                                     } else if ("class java.math.BigDecimal".equals(xclass)) {
106                                     //精度丢失
107                                         setMethod.invoke(tObject, new BigDecimal(cell.getNumericCellValue()));
108                                     } else {
109                                         // 
110                                     }
111                                 }
112                             }
113                         } catch (Exception e) {
114                             outMessage = outMessage+"第"+countRow+"行,第"+countCloum+"列;";
115                             importRslt.put("status", "ERROR");
116                         }
117                         dist.add(tObject);
118                     }
119                 }
120             }
121             if(!outMessage.isEmpty())
122                 outMessage = outMessage+"格式有误!!!";
123             else
124                 outMessage = "读取成功,共读取"+countRow+"行!!!";
125         }catch(Exception ex)
126         {
127             outMessage = "读取文档有误!!!";
128             importRslt.put("status", "ERROR");
129         }
130         importRslt.put("rslt", dist);
131         importRslt.put("msg", outMessage);
132         return importRslt;
133     }
134 }
View Code

本段代码在将excel中的浮点数转化成实体类对应的bigdecimal或者double时会发生精度丢失导致上传数据出错。这种通过excelutil上传文件通常用来处理字段全为String类型的数据上传。

 2.jsp点击导入文件,type为file,与上传文件一样。

onchange、onload、onsubmit、onblur与onclick事件
onchange:内容发生改变时触发事件。
onclick:点击时触发事件
onsubmit:表单提交,通常用在表单提交时的表单的数据验证
onblur:失去焦点事件
onload:加载完成事件

3.controller层(注意:业务应该写在service层)

 1 //使用MultipartFile接受上传的文件信息
 2 @RequestMapping(value = "/importExcelData")
 3      public @ResponseBody String importExcelData(@RequestParam(value = "uploadContractFile") MultipartFile mFile, HttpServletRequest request) {
 4         AjaxObject ajaxObject = new AjaxObject();
 5         //获取当前登录人的信息
 6         Subject subject = SecurityUtils.getSubject();
 7         MyShiroRealm.ShiroUser shiroUser = (MyShiroRealm.ShiroUser) subject.getPrincipal();
 8         String userName = shiroUser.getUser().getStrAccount();
 9         //获取上传文件的文件名
10         String strFileName = mFile.getOriginalFilename();
11           try {
12           //将上传文件保存在项目中的资源文件里
13             commonService.uploadFile(mFile, request, "fcHydrantFile", "", "imFile", "");
14         } catch (Exception e1) {
15             // TODO Auto-generated catch block
16             e1.printStackTrace();
17         }
18           //
19           String path = "/static/uploadFiles/fcHydrantFile/"+userName+"/"+strFileName;
20           ExcelUtil<FcHydrantEntity> excelUtil = new ExcelUtil<FcHydrantEntity>(FcHydrantEntity.class);
21           //获取文件的绝对路径
22           String rpath = request.getSession().getServletContext().getRealPath(path);
23           //通过路径将保存在项目中的文件转成file类型
24           File file = new File(rpath);
25           ControllerUtil controllerUtil = new ControllerUtil();
26           int i = 0;
27           try {
28           //将文件中的数据转成list
29               List<FcHydrantEntity> dlist = (List<FcHydrantEntity>)excelUtil.importExcel(file, "");
30               //遍历list转成实体类create到数据库中
31               for(FcHydrantEntity fcHydrant : dlist) {
32                   if(fcHydrant == null) {
33                       continue;
34                   }
35                   EntityUtil.setUpdateProp(fcHydrant);
36                   fcHydrantService.create(fcHydrant);
37                   i++;
38               }
39               ajaxObject.setMessage("成功导入"+i+"条数据!");
40           }catch (Exception e){
41               e.printStackTrace();
42                 logger.error(e.getMessage(), e);
43                 ajaxObject.setStatusCode(AjaxObject.STATUS_CODE_FAILURE);
44                 ajaxObject.setMessage("成功导入"+i+"条数据!第"+(i+1)+"导入失败!");    
45           }
46         return ajaxObject.toString();
47     }
View Code
posted @ 2019-12-30 10:25  leviH  阅读(345)  评论(0编辑  收藏  举报