java 使用poi操作Excel(2003,2007)实现数据批量导入的一般思路

(本文原创-引用请注明出处 -- zhangjieatbky)

  • 对于批量导入,首先建立实体类,其中增加行号和状态两个字段,用来定位有问题的行
 1 public class BatchImportBean {
 2     private int no;
 3     private boolean isValid;
 4     private String objectName;
 5     private String licenseNo;
 6     private String trustLessInfo;        //失信性质
 7     private String illegalKind;            //违法类别
 8     private String catalogName;
 9     private String processString;          //处罚时间,String类型
10     private String beListedReason;        //列入名单的原因
11     private String limitStringBegin;         //限制日期自,String类型
12     private String limitStringEnd;         //限制日期至,String类型
13     private String linkman;
14     private String linkmanPhone;
15     private String remark;
16     private String punishKind;            //需要将id解析成中文名称
17     private String detailPunishKind;    //具体的行政处罚种类
18     private long punishPaid;            //处罚金额,浮点数
19     private long illegalIncome;        //没收违法所得,浮点数
20     private String stopTime;            //停产时长,根据数字解析成中文
21     private String cancelItem;            //被吊销的许可证所涉审批项目
22     private String cancelIDName;        //被吊销的许可证名称
23     private String cancelIDNo;            //被吊销的许可证/批准文件编号
24     ...
  • 判断是否有空行,如果有,则略过空行
/**
     * 判断所有数据是否为空,若为空,则跳过该数据
     * @return
     */
    
    private static boolean isAllDataEmpty(List<String> list){
        int emptyStrs = 0;
        for(String temp : list){
            if(temp.trim().equals("")){
                emptyStrs++;
                continue;
            }
        }
        return emptyStrs == list.size();
    }
  • 编写校验方法,对Excel中不符合业务要求或数据字段大小、类型等对比判断
  1 /**
  2      * 
  3      * @param list   excel 中的一行数据,全部以字符串形式读取
  4      * @param obj    保存该条数据的对象
  5      * @param index 所在行号
  6      * @return
  7      */
  8     public static BatchImportBean validateBatchImportObject(List<String> list,int index){
  9         Pattern p = Pattern.compile("[1][9][0-9][0-9]/[0]?[1-9]/[0]?[1-9]$|[1][9][0-9][0-9]/[0]?[1-9]/[1-2][0-9]|[1][9][0-9][0-9]/[0]?[1-9]/[3][0-1]"//2017/3/9
 10                 + "|[1][9][0-9][0-9]/[1][0-2]/[0]?[1-9]$|[1][9][0-9][0-9]/[1][0-2]/[1-2][0-9]|[1][9][0-9][0-9]/[1][0-2]/[3][0-1]"
 11                 + "|[2][0][0-9][0-9]/[0]?[1-9]/[0]?[1-9]$|[2][0][0-9][0-9]/[0]?[1-9]/[1-2][0-9]|[2][0][0-9][0-9]/[0]?[1-9]/[3][0-1]"
 12                 + "|[2][0][0-9][0-9]/[1][0-2]/[0]?[1-9]$|[2][0][0-9][0-9]/[1][0-2]/[1-2][0-9]|[2][0][0-9][0-9]/[1][0-2]/[3][0-1]");
 13         //非空校验和长度校验  ,企业名称/xingmi
 14         BatchImportBean obj = new BatchImportBean();
 15         if(list.get(0).trim().equals("") || list.get(0).getBytes().length>=100){
 16             obj.setNo(index+1);
 17             obj.setValid(false);
 18             return obj;
 19         }
 20         //非空校验和长度校验  ,证照号码
 21         if(list.get(1).trim().equals("") || list.get(1).getBytes().length>=30){
 22             obj.setNo(index+1);
 23             obj.setValid(false);
 24             return obj;
 25         }
 26         //非空校验和长度校验  ,失信性质
 27         if(list.get(2).trim().equals("") || list.get(2).getBytes().length>=50){
 28             obj.setNo(index+1);
 29             obj.setValid(false);
 30             return obj;
 31         }
 32         //非空校验和长度校验  ,违法类别
 33         if(list.get(3).trim().equals("") || list.get(3).getBytes().length>=50){
 34             obj.setNo(index+1);
 35             obj.setValid(false);
 36             return obj;
 37         }
 38         //非空校验和长度校验  ,联合惩戒目录名称  
 39         if(list.get(4).trim().equals("") || list.get(4).getBytes().length>=100){
 40             obj.setNo(index+1);
 41             obj.setValid(false);
 42             return obj;
 43         }
 44         //非空检验和格式校验, 处罚日期 , 正则匹配
 45         if(list.get(5).trim().equals("") || list.get(5).getBytes().length>=100 || !p.matcher(list.get(5).trim()).find()){
 46             obj.setNo(index+1);
 47             obj.setValid(false);
 48             return obj;
 49         }
 50         //非空检验和长度校验, 列入名单原因
 51         if(list.get(6).trim().equals("") || list.get(6).getBytes().length>=600){
 52             obj.setNo(index+1);
 53             obj.setValid(false);
 54             return obj;
 55         }
 56         //非空校验和格式校验,限制日期自
 57         if(list.get(7).trim().equals("") || !p.matcher(list.get(7).trim()).find()){
 58             obj.setNo(index+1);
 59             obj.setValid(false);
 60             return obj;
 61         }
 62         //格式校验,没有非空校验,限制日期至
 63         if(!p.matcher(list.get(8).trim()).find()){
 64             if(list.get(8).trim().equals("")){
 65                 
 66             }else{
 67                 obj.setNo(index+1);
 68                 obj.setValid(false);
 69                 return obj;
 70             }
 71         }
 72         //非空校验和格式校验,联系人
 73         if(list.get(9).trim().equals("") || list.get(9).getBytes().length>=100){
 74             obj.setNo(index+1);
 75             obj.setValid(false);
 76             return obj;
 77         }
 78         //非空校验和格式校验,联系电话
 79         if(list.get(10).trim().equals("") || list.get(10).getBytes().length>=20){
 80             obj.setNo(index+1);
 81             obj.setValid(false);
 82             return obj;
 83         }
 84         //长度校验,备注
 85         if(list.get(11).getBytes().length>=4000){
 86             obj.setNo(index+1);
 87             obj.setValid(false);
 88             return obj;
 89         }
 90         //非空校验,行政处罚种类
 91         if(list.get(12).trim().equals("")){
 92             obj.setNo(index+1);
 93             obj.setValid(false);
 94             return obj;
 95         }
 96         //根据行政处罚种类的选择判断其他非空,注意:这里是完整匹配
 97         if(list.get(12).trim().contains("法律、行政法规规定的其他行政处罚") && list.get(13).trim().equals("") && list.get(13).getBytes().length>=200){
 98             obj.setNo(index+1);
 99             obj.setValid(false);
100             return obj;
101         }
102         //匹配 罚款    
103         if(list.get(12).trim().contains("罚款") && list.get(14).trim().equals("") && list.get(14).getBytes().length>=21){
104             obj.setNo(index+1);
105             obj.setValid(false);
106             return obj;
107         }
108         //匹配 没收违法所得
109         if(list.get(12).trim().contains("没收违法所得") && list.get(15).trim().equals("") && list.get(15).getBytes().length>=21){
110             obj.setNo(index+1);
111             obj.setValid(false);
112             return obj;
113         }
114         //匹配停产时长  ,正则校验 
115         p=Pattern.compile("^[1-9][0-9]*个月|无限期");
116         if(list.get(12).trim().contains("责令停产") && list.get(16).trim().equals("")){
117             obj.setNo(index+1);
118             obj.setValid(false);
119             return obj;
120         }else if(list.get(12).trim().contains("责令停产") && !p.matcher(list.get(16).trim()).find()){
121             obj.setNo(index+1);
122             obj.setValid(false);
123             return obj;
124         }
125         //匹配 吊销许可证 ,只针对所涉审批项目 一项校验
126         if(list.get(12).trim().contains("吊销许可证") && (list.get(17).trim().equals(""))){        
127             obj.setNo(index+1);
128             obj.setValid(false);
129             return obj;
130         }
131         
132         //校验通过之后开始初始化参数对象obj
133         obj.setObjectName(list.get(0).trim());
134         obj.setLicenseNo(list.get(1).trim());
135         obj.setTrustLessInfo(list.get(2).trim());
136         obj.setIllegalKind(list.get(3).trim());
137         obj.setCatalogName(list.get(4).trim());
138         obj.setProcessString(list.get(5).trim().split("/")[0]+"-"+list.get(5).trim().split("/")[1]+"-"+list.get(5).trim().split("/")[2]);
139         obj.setBeListedReason(list.get(6).trim());
140         Calendar calendar1 = Calendar.getInstance();
141         calendar1.set(Integer.parseInt(list.get(7).trim().split("/")[0]), Integer.parseInt(list.get(7).trim().split("/")[1])-1, Integer.parseInt(list.get(7).trim().split("/")[2]));
142         obj.setLimitStringBegin(list.get(7).trim().split("/")[0]+"-"+list.get(7).trim().split("/")[1]+"-"+list.get(7).trim().split("/")[2]);
143         if(!list.get(8).trim().equals("")){
144             Calendar calendar2 = Calendar.getInstance();
145             calendar2.set(Integer.parseInt(list.get(8).trim().split("/")[0]), Integer.parseInt(list.get(8).trim().split("/")[1])-1, Integer.parseInt(list.get(8).trim().split("/")[2]));
146             obj.setLimitStringEnd(list.get(8).trim().split("/")[0]+"-"+list.get(8).trim().split("/")[1]+"-"+list.get(8).trim().split("/")[2]);
147             if(calendar1.getTime().after(calendar2.getTime())){        //限制日期之间的比较
148                 obj.setNo(index+1);
149                 obj.setValid(false);
150                 return obj;
151             }
152         }else{
153             obj.setLimitStringEnd("");
154         }
155         obj.setLinkman(list.get(9).trim());
156         obj.setLinkmanPhone(list.get(10).trim());
157         obj.setRemark(list.get(11).trim());
158         obj.setPunishKind(list.get(12).trim().replace("警告","1").replace("罚款","2").replace("没收违法所得","32").replace("没收非法财物","31").
159                 replace("责令停产","41").replace("责令停业", "42").replace("暂扣许可证","5").replace("吊销许可证","7").replace("暂扣执照","6").
160                 replace("吊销执照","8").replace("行政拘留","11").replace("其他行政处罚","99"));
161         if(list.get(12).trim().contains("法律、行政法规规定的其他行政处罚"))
162             obj.setDetailPunishKind(list.get(13).trim());
163         else
164             obj.setDetailPunishKind("");
165         if(list.get(12).trim().contains("罚款")){
166             if(list.get(14).trim().equals("")){
167                 obj.setNo(index+1);
168                 obj.setValid(false);
169                 return obj;
170             }
171             obj.setPunishPaid(Long.parseLong(((new BigDecimal(list.get(14).trim()).multiply(new BigDecimal("1000000"))+"").split("\.")[0])));
172         }
173         else
174             obj.setPunishPaid(0);            //还要转为""
175         if(list.get(12).trim().contains("没收违法所得")){
176             if(list.get(15).trim().equals("")){
177                 obj.setNo(index+1);
178                 obj.setValid(false);
179                 return obj;
180             }
181             obj.setIllegalIncome(Long.parseLong(((new BigDecimal(list.get(15).trim()).multiply(new BigDecimal("1000000"))+"").split("\.")[0])));
182         }
183         else
184             obj.setIllegalIncome(0);        //还要转为""
185         p=Pattern.compile("(^[1-9][0-9]*)个月|无限期");
186         Matcher m = p.matcher(list.get(16).trim());
187         m.find();
188         if(list.get(12).trim().contains("责令停产")){
189             if(list.get(16).trim().equals("无限期"))
190                 obj.setStopTime("-1");
191             else
192                 obj.setStopTime(m.group(1));
193         }else
194             obj.setStopTime("");
195         if(list.get(12).trim().contains("吊销许可证")){
196             obj.setCancelItem(list.get(17).trim());
197             obj.setCancelIDName(list.get(18).trim());
198             obj.setCancelIDNo(list.get(19).trim());
199         }
200         else{
201             obj.setCancelItem("");
202             obj.setCancelIDName("");
203             obj.setCancelIDNo("");
204         }
205         obj.setNo(index+1);
206         obj.setValid(true);
207         return obj;
208     }
  • 对实体类中的valid属性进行检查,即检查Excel的数据完整性、合理性。不符合要求则不进行导入
 1 /**
 2      * 校验批量导入的数据(内存中的)
 3      * @return
 4      */
 5     public static EditJson validateBatchImportList(List<BatchImportBean>list){
 6         EditJson editJson = new EditJson();
 7         editJson.setSuccess(true);
 8         List<Integer> errorDataNo = new ArrayList<Integer>();
 9         for(BatchImportBean obj : list ){
10             if(!obj.isValid()){
11                 editJson.setSuccess(false);
12                 errorDataNo.add(obj.getNo());
13             }
14         }
15         if(!editJson.isSuccess())
16             editJson.setBean(errorDataNo.toString());        //失败返回行索引
17         return editJson;        //现在将数据存放在session中了,如果成功,不需要将数据再带回到前台了
18     }
  • 读取批量导入的数据,以java对象的形式通过list集合进行组织
  •  1 /**
     2      * 读取批量导入的数据,共20个字段
     3      * @param columns
     4      * @param is
     5      * @param fileType
     6      * @return
     7      * @throws IOException
     8      */
     9     public static List<BatchImportBean> readBatchImportObject(int columns,InputStream is,String fileType)throws IOException{
    10         Workbook workbook = null;
    11         if(fileType.equals("*.xls"))
    12             workbook = new HSSFWorkbook(is);
    13         else if(fileType.equals("*.xlsx"))
    14             workbook = new XSSFWorkbook(is);
    15         Sheet sheet = workbook.getSheetAt(0);
    16         List<BatchImportBean> result = new ArrayList<BatchImportBean>();
    17         DataFormatter formatter = new DataFormatter();
    18         String cellContent = null;
    19         int i =0;
    20         int rowLength = sheet.getLastRowNum();
    21         
    22         Row tempRow =null;
    23         for(int k=4;k<=rowLength;k++){            //数据起始行,除了说明、标题
    24 //            BatchImportBean tempBean = new BatchImportBean();
    25             List<String> rowContent = new ArrayList<String>();        //以字符串的形式接受数据
    26             rowContent.clear();
    27             tempRow = sheet.getRow(k);
    28             if(tempRow == null)
    29                 continue;
    30             for(int j=0;j<columns;j++){        //指定遍历的列数
    31                 Cell cell = tempRow.getCell(j,Row.RETURN_BLANK_AS_NULL);
    32                 if(cell == null){
    33                     cellContent = "";
    34                     System.out.print("blank"+'	');
    35                     i++;
    36                 }else{
    37                     switch(cell.getCellType()){
    38                     case Cell.CELL_TYPE_STRING :
    39                         System.out.print(formatter.formatCellValue(cell)+'	');
    40                         cellContent = formatter.formatCellValue(cell)+"";
    41                         i++;
    42                         break;
    43                     case Cell.CELL_TYPE_NUMERIC:
    44                         System.out.print(formatter.formatCellValue(cell)+'	');
    45                         cellContent = formatter.formatCellValue(cell)+"";
    46                         i++;
    47                         break;
    48                     case Cell.CELL_TYPE_BOOLEAN:
    49                         System.out.print(formatter.formatCellValue(cell)+'	');
    50                         cellContent = formatter.formatCellValue(cell)+"";
    51                         i++;
    52                         break;
    53                     case Cell.CELL_TYPE_FORMULA:
    54                         cellContent = "";
    55                         System.out.print("formular"+'	');
    56                         i++;
    57                         break;
    58                     case Cell.CELL_TYPE_BLANK:
    59                         cellContent = "";
    60                         System.out.print("blank"+'	');
    61                         i++;
    62                         break;
    63                     default:
    64                         cellContent = "";
    65                         System.out.println("default..."+'	');
    66                         i++;
    67                     }
    68                 }
    69                 if(i%columns == 1) rowContent.add(cellContent);// tempBean.setObjectName(cellContent);        
    70                 else if(i%columns == 2) rowContent.add(cellContent);// tempBean.setLicenseNo(cellContent);
    71                 else if(i%columns == 3) rowContent.add(cellContent); // tempBean.setTrustLessInfo(cellContent);        //失信性质
    72                 else if(i%columns == 4) rowContent.add(cellContent); // tempBean.setIllegalKind(cellContent);        //违法类别
    73                 else if(i%columns == 5) rowContent.add(cellContent);// tempBean.setCatalogName(cellContent);        //目录名称
    74                 else if(i%columns == 6) rowContent.add(cellContent);//tempBean.setProcessDate(cellContent);        //处罚时间
    75                 else if(i%columns == 7) rowContent.add(cellContent);// tempBean.setBeListedReason(cellContent);        //列入名单的原因
    76                 else if(i%columns == 8) rowContent.add(cellContent);//tempBean.setLimitDateBegin(cellContent);        //限制日期自
    77                 else if(i%columns == 9) rowContent.add(cellContent);//tempBean.setLimitDateEnd(cellContent);            //限制日期至
    78                 else if(i%columns == 10) rowContent.add(cellContent);//tempBean.setLinkman(cellContent);                //联系人
    79                 else if(i%columns == 11) rowContent.add(cellContent);//tempBean.setLinkmanPhone(cellContent);            //联系电话
    80                 else if(i%columns == 12) rowContent.add(cellContent);//tempBean.setRemark(cellContent);                //备注
    81                 else if(i%columns == 13) rowContent.add(cellContent);//tempBean.setPunishKind(cellContent);            //处罚种类,需要解析id
    82                 else if(i%columns == 14) rowContent.add(cellContent);//tempBean.setDetailPunishKind(cellContent);        //具体的行政处罚种类
    83                 else if(i%columns == 15) rowContent.add(cellContent);//tempBean.setPunishPaid(cellContent);            //处罚金额,double类型
    84                 else if(i%columns == 16) rowContent.add(cellContent);//tempBean.setIllegalIncome(cellContent);            //没收违法所得,double类型
    85                 else if(i%columns == 17) rowContent.add(cellContent);//tempBean.setStopTime(cellContent);                //停产时长,解析id
    86                 else if(i%columns == 18) rowContent.add(cellContent);//tempBean.setCancelItem(cellContent);            //被吊销的许可证所涉审批项目            
    87                 else if(i%columns == 19) rowContent.add(cellContent);//tempBean.setCancelIDName(cellContent);            //被吊销的许可证名称
    88                 else if(i%columns == 0) rowContent.add(cellContent);//tempBean.setCancelIDNo(cellContent);            //被吊销的许可证/批准文件编号
    89             }
    90             if(isAllDataEmpty(rowContent)) continue;
    91             result.add(validateBatchImportObject(rowContent,k));
    92         }
    93         System.out.println(result);
    94         return result;
    95     }
原文地址:https://www.cnblogs.com/zhangjieatbky/p/8137409.html