ChenJiaHe
2021-01-27 132d1a41ca120a6bc212a43ea2925e51128abbb7
提交 | 用户 | age
5c5945 1 package com.hx.util;
E 2
3 import java.io.BufferedReader;
4 import java.io.DataOutputStream;
5 import java.io.File;
6 import java.io.FileInputStream;
7 import java.io.IOException;
8 import java.io.UnsupportedEncodingException;
9 import java.math.BigDecimal;
10 import java.math.RoundingMode;
11 import java.net.FileNameMap;
12 import java.net.HttpURLConnection;
13 import java.net.InetAddress;
14 import java.net.URL;
15 import java.net.URLConnection;
16 import java.net.URLDecoder;
17 import java.net.UnknownHostException;
18 import java.security.MessageDigest;
19 import java.security.NoSuchAlgorithmException;
20 import java.sql.Timestamp;
21 import java.text.DateFormat;
22 import java.text.DecimalFormat;
23 import java.text.ParseException;
24 import java.text.SimpleDateFormat;
db7fc9 25 import java.util.*;
5c5945 26 import java.util.regex.Matcher;
E 27 import java.util.regex.Pattern;
28
29 import javax.servlet.http.HttpServletRequest;
30
31 import org.apache.commons.io.IOUtils;
32 import org.apache.poi.hssf.usermodel.HSSFCell;
33 import org.apache.poi.hssf.usermodel.HSSFDataFormatter;
34 import org.apache.poi.hssf.usermodel.HSSFDateUtil;
35 import org.apache.poi.hssf.usermodel.HSSFRow;
36 import org.apache.poi.hssf.usermodel.HSSFSheet;
37 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
38 import org.apache.poi.ss.usermodel.Cell;
39
40 import net.sf.json.JSONArray;
41 import net.sf.json.JSONException;
42 import net.sf.json.JSONObject;
43 import net.sourceforge.pinyin4j.PinyinHelper;
44 import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
45 import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
132d1a 46 import org.springframework.cglib.beans.BeanMap;
5c5945 47
E 48 public class SimpleTool {
49
50     public static SimpleDateFormat myformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
51     public static DecimalFormat fmt = new DecimalFormat("0.00");
52     public static Byte[] lock = new Byte[] {0};
db7fc9 53
C 54     /**对象转map*/
55     public static Map<?, ?> objectToMap(Object obj) {
56         if(obj == null)
57             return null;
58
59         return new org.apache.commons.beanutils.BeanMap(obj);
60     }
61
5c5945 62     /**
132d1a 63      * 将对象装换为map
C 64      *
65      * @param bean
66      * @return
67      */
68     public static <T> Map<String, Object> beanToMap(T bean) {
69         Map<String, Object> map = new HashMap<>();
70         if (bean != null) {
71             BeanMap beanMap = BeanMap.create(bean);
72             for (Object key : beanMap.keySet()) {
73                 map.put(key + "", beanMap.get(key));
74             }
75         }
76         return map;
77     }
78
79
80     /**
5c5945 81      * 后台格式构建返回值格式列表-后台获取列表
E 82      * @param count 返回总条数
83      * @return JSONObject 特定格式的JSONObject
84      */
85     public static JSONObject resAdminLsit(Integer status,String errMsg,JSONArray arr,Integer count){
86         
87         JSONObject fObj = new JSONObject();
88         try{
89             fObj.put("code", status);
90             fObj.put("count", count);
91             fObj.put("msg", errMsg);                        
92             fObj.put("data", arr);
93         }catch (Exception e) {
94             e.printStackTrace();
95         }
96         return fObj;
97     }
98     
99     /**
100      * 获取指定格式的Double 类型数据
101      * 
102      * @param type
103      *            转换格式的类型 默认为 "#.#"
104      * @param e
105      *            要转换的数据源
106      **/
107     public static Double getTypeDouble(String type, Double e) {
108         if (!checkNotNull(type))
109             type = "0.00";
110         fmt = new DecimalFormat(type);
111         fmt.setRoundingMode(RoundingMode.HALF_UP); // 保留小数点后两位并四舍五入,确保价钱准确
112         Double d = Double.valueOf(fmt.format(e));
113         return d;
114     }
115
116     /**
117      * 首字母大写
118      * 
119      * @param str
120      */
121     public static String capitalized(String str) {
122         if ("".equals(str.trim()) || str == null) {
123             return "";
124         }
125         String key = str.substring(0, 1).toUpperCase();
126         String keys = key + str.substring(1, str.length());
127         return keys;
128     }
129
130     /** 判断参数是否为null,如果null抛出对应异常 */
131     public static void checkErrMsg(Object obj, String errMsg) {
132         if (!checkNotNull(obj))
133             throw new RuntimeException(errMsg);
134     }
135
136     /*** 创建文件(自动生成文件夹。)(需要真实路径) **/
137     public static File createFile(String mkdirPath, String fileName) throws IOException {
138         System.out.println(mkdirPath + fileName);
139         // mkdirPath =
140         // "E:\\work\\soft\\MyEclipse\\apache-tomcat-7.0.61\\webapps\\ROOT\\";
141
142         File f = new File(mkdirPath);
143         if (!f.exists()) {
144             f.mkdirs();
145         }
146         File file = new File(f, fileName);
147         if (!file.exists()) {
148             file.createNewFile();
149         }
150
151         // System.out.println(file.getAbsolutePath());
152         return file;
153     }
154
155     /**
156      * 构建返回值格式
157      * 
158      * @param status
159      *            返回状态
160      * @param errMsg
161      *            返回附带信息
162      * @param inf
163      *            返回实体值
164      * @return JSONObject 特定格式的JSONObject
165      */
166     public static JSONObject res(Integer status, String errMsg, JSONObject inf) {
167         JSONObject res = new JSONObject();
168         JSONObject fObj = new JSONObject();
169         try {
170             res.put("status", status);
171             res.put("errMsg", errMsg);
172
173             fObj.put("res", res);
174             fObj.put("inf", inf);
175         } catch (Exception e) {
176             e.printStackTrace();
177         }
178         return fObj;
179     }
180
181     /**
182      * Date类型转换为10位时间戳
183      * 
184      * @param time
185      * @return
186      */
187     public static Integer DateToTimestamp(Date time) {
188         Timestamp ts = new Timestamp(time.getTime());
189         return (int) ((ts.getTime()) / 1000);
190     }
191
192     /** 判断当前时间是什么时候 **/
193     public static Boolean IsTime(Date date, Integer year, Integer month, Integer day, Integer hour, Integer minute) {
194         Calendar cal = new GregorianCalendar();
195         cal.setTime(date);
196         if (year != null) {
197             int iyear = cal.get(Calendar.YEAR);
198             if (iyear != year)
199                 return false;
200         }
201
202         if (month != null) {
203             int imonth = cal.get(Calendar.MONTH);// 获取月份(月份从0开始计算的)
204             imonth = imonth + 1;
205             if (imonth != month)
206                 return false;
207         }
208
209         if (day != null) {
210             int iday = cal.get(Calendar.DATE);// 获取日
211             if (iday != day)
212                 return false;
213         }
214
215         if (hour != null) {
216             int ihour = cal.get(Calendar.HOUR_OF_DAY);// 24小时 0- 23
217             if (ihour != hour)
218                 return false;
219         }
220
221         if (minute != null) {
222             int iminute = cal.get(Calendar.MINUTE);
223             if (iminute != minute)
224                 return false;
225         }
226         // Boolean b = yearTag && monthTag && dayTag && hourTag && minuteTag;
227         return true;
228     }
229
230     /**
231      * 根据具体时间属性判断是否相同
232      * 
233      */
234     public static Boolean DateEquals(Date date1, Date date2, Boolean year, Boolean month, Boolean day, Boolean hour,
235             Boolean minute) {
236
237         Calendar calendar1 = new GregorianCalendar();
238         Calendar calendar2 = new GregorianCalendar();
239         calendar1.setTime(date1);
240         calendar2.setTime(date2);
241
242         if (year) {
243             if (calendar1.get(Calendar.YEAR) != calendar2.get(Calendar.YEAR)) {
244                 return false;
245             }
246         }
247         if (month) {
248             if (calendar1.get(Calendar.MONTH) != calendar2.get(Calendar.MONTH)) {
249                 return false;
250             }
251         }
252         if (day) {
253             if (calendar1.get(Calendar.DATE) != calendar2.get(Calendar.DATE)) {
254                 return false;
255             }
256         }
257         if (year) {
258             if (calendar1.get(Calendar.HOUR_OF_DAY) != calendar2.get(Calendar.HOUR_OF_DAY)) {
259                 return false;
260             }
261         }
262         if (year) {
263             if (calendar1.get(Calendar.MINUTE) != calendar2.get(Calendar.MINUTE)) {
264                 return false;
265             }
266         }
267
268         // Boolean b = yearTag && monthTag && dayTag && hourTag && minuteTag;
269
270         return true;
271     }
272
273     /** 获取10位数时间戳 */
274     public static Integer getTenTime(Date date) {
275         Timestamp ts = new Timestamp(date.getTime());
276         return (int) ((ts.getTime()) / 1000);
277     }
278
279     /**
280      * 获取指定日期的明天 difDay 把日期往后增加一天.整数往后推,负数往前移动
281      * 
282      * @return date
283      */
284     @SuppressWarnings("static-access")
285     public static Date getDetailDay(Date today, int difDay) {
286         Calendar calendar = new GregorianCalendar();
287         calendar.setTime(today);
288         calendar.add(calendar.DATE, difDay);// 把日期往后增加一天.整数往后推,负数往前移动
289         Date d = calendar.getTime();
290         return d;
291     }
292
293    /**
294      * 获取想要的格式的时间
295      * 
296      * @return String
297      */
298     public static String getTypeDate(String type, Date date) {
299         if (date == null)
300             return null;
301
302         if (SimpleTool.checkNotNull(type)) {
303             myformat = new SimpleDateFormat(type);
304             String returnDate = myformat.format(date);
305             myformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
306             return returnDate;
307         } else {
308             String returnDate = myformat.format(date);
309             return returnDate;
310         }
311
312     } 
313
314     /**
315      * 比较两个时间天数差 startTime - endTime
316      * 
317      * @param type
318      *            (无效)
319      * @return String
320      * @throws ParseException
321      */
322     public static int getDiffDate(String type, Date startTime, Date endTime) throws ParseException {
323         type = "yyyyMMdd";
324         SimpleDateFormat myformat = new SimpleDateFormat(type);
325         int i = 0;
326         i = (int) ((myformat.parse(myformat.format(startTime)).getTime()
327                 - myformat.parse(myformat.format(endTime)).getTime()) / (1000 * 60 * 60 * 24));
328         // return
329         // myformat.parse(myformat.format(date1)).compareTo(myformat.parse(myformat.format(date2)));
330         return i;
331     }
332
333     /**
334      * 得到两个时间的分钟差 date1 - date2 这个是个奇葩。但是整型了。
335      * 
336      * @return int
337      * @throws ParseException
338      */
339     public static int getLeftDateForMinue(Date date1, Date date2) throws ParseException {
340         long times = date1.getTime() - date2.getTime();
341         times = times / (1000 * 60);
342         return (int) times;
343     }
344
345     /**把字符串转为特定时间格式
346      * 
347      * @param type 时间格式
348      * @param sDate 字符串时间(可以为空)
349      * @return date
350      * @throws ParseException
351      */
352     public static Date parseStringForDate(String type, String sDate){
353         Date date = null;
354         try {
355             if(SimpleTool.checkNotNull(sDate)) {
356                 SimpleDateFormat myformat = new SimpleDateFormat(type);
357                 date = myformat.parse(sDate);
358             }
359         } catch (Exception e) {
360             e.printStackTrace();
361         }
362         return date;
363     }
364
365     /**
366      * 判断是否为空
367      */
368     public static boolean checkNotNull(Object o) {
369         boolean b = false;
370         if (o != null && !"".equals(o)&&!"undefined".equals(o)&&!" ".equals(o)) {
371             b = true;
372         }
373         return b;
374     }
375
376     /**
377      * 判断是否为空 (多个)
378      */
379     public static boolean checkNotNullM(Object[] os) {
380         boolean b = true;
381         for (Object o : os) {
382             if (o == null || "".equals(o))
383                 return false;
384         }
385         return b;
386     }
387
388     /**
389      * 获取服务器端的webapps路径
390      * 
391      * @return
392      */
393     public String findServerPath() {
394         String classPath = this.getClass().getClassLoader().getResource("/").getPath();
395         try {
396             classPath = URLDecoder.decode(classPath, "gb2312");
397         } catch (UnsupportedEncodingException e) {
398             e.printStackTrace();
399         }
400         String[] strPath = classPath.split("/");
401         String path = "";
402         for (int i = 0; i < strPath.length; i++) {
403             if (i > 0 && i <= 3) {
404                 path = path + strPath[i] + "/";
405             }
406         }
407         return path;
408     }
409
410     /**
411      * 删除文件 输入真是路径
412      */
413     public static void deleteFile(String sPath) {
414         File file = new File(sPath);
415         // 判断目录或文件是否存在
416         if (file.exists()) {
417             // 判断是否为文件
418             if (file.isFile()) { // 为文件时调用删除文件方法
419                 deleteFileForOne(sPath);
420             } else { // 为目录时调用删除目录方法
421                 throw new RuntimeException("dir is no del");
422                 // deleteDirectory(sPath);
423             }
424         }
425     }
426
427     /**
428      * 删除目录(文件夹)以及目录下的文件
429      * 
430      * @param sPath
431      *            被删除目录的文件路径
432      * @return 目录删除成功返回true,否则返回false
433      */
434     public static boolean deleteDirectory(String sPath) {
435         // 如果sPath不以文件分隔符结尾,自动添加文件分隔符
436         if (!sPath.endsWith(File.separator)) {
437             sPath = sPath + File.separator;
438         }
439         File dirFile = new File(sPath);
440         // 如果dir对应的文件不存在,或者不是一个目录,则退出
441         if (!dirFile.exists() || !dirFile.isDirectory()) {
442             return false;
443         }
444         Boolean flag = true;
445         // 删除文件夹下的所有文件(包括子目录)
446         File[] files = dirFile.listFiles();
447         for (int i = 0; i < files.length; i++) {
448             // 删除子文件
449             if (files[i].isFile()) {
450                 flag = deleteFileForOne(files[i].getAbsolutePath());
451                 if (!flag)
452                     break;
453             } // 删除子目录
454             else {
455                 flag = deleteDirectory(files[i].getAbsolutePath());
456                 if (!flag)
457                     break;
458             }
459         }
460         if (!flag)
461             return false;
462         // 删除当前目录
463         if (dirFile.delete()) {
464             return true;
465         } else {
466             return false;
467         }
468     }
469
470     /**
471      * 删除单个文件
472      * 
473      * @param sPath
474      *            被删除文件的文件名
475      * @return 单个文件删除成功返回true,否则返回false
476      */
477     public static boolean deleteFileForOne(String sPath) {
478         Boolean flag = false;
479         File file = new File(sPath);
480         // 路径为文件且不为空则进行删除
481         if (file.isFile() && file.exists()) {
482             file.delete();
483             flag = true;
484         }
485         return flag;
486     }
487
488
489     /**
490      * 获取uuid
491      */
492     public static String getUUIDName() {
493         return UUID.randomUUID().toString();
494     }
495
496
497     /** 获取异常信息 **/
498     public static String getExceptionMsg(Exception e) {
499         StringBuffer emsg = new StringBuffer();
500         if (e != null) {
501             StackTraceElement[] st = e.getStackTrace();
502             for (StackTraceElement stackTraceElement : st) {
503                 String exclass = stackTraceElement.getClassName();
504                 String method = stackTraceElement.getMethodName();
505                 emsg.append("[类:" + exclass + "]调用---" + method + "----时在第" + stackTraceElement.getLineNumber()
506                         + "行代码处发生异常!异常类型:" + e.toString() + "(" + e.getMessage() + ")\r\n");
507             }
508         }
509         return emsg.toString();
510     }
511
512     /**
513      * 获取指定格式的Double 类型数据
514      *
515      *            转换格式的类型 默认为 "#.##"
516      * @param e
517      *            要转换的数据源
518      **/
519     public static Double getTypeDouble(Double e) {
520         fmt.setRoundingMode(RoundingMode.HALF_UP); // 保留小数点后两位并四舍五入,确保价钱准确
521         Double d = Double.valueOf(fmt.format(e));
522         return d;
523     }
524
525
526     /**
527      * SHA1 加密
528      * 
529      * @param decript
530      * @return
531      */
532     public static String SHA1(String decript) {
533         try {
534             MessageDigest digest = MessageDigest.getInstance("SHA-1");
535             digest.update(decript.getBytes());
536             byte messageDigest[] = digest.digest();
537             // Create Hex String
538             StringBuffer hexString = new StringBuffer();
539             // 字节数组转换为 十六进制 数
540             for (int i = 0; i < messageDigest.length; i++) {
541                 String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
542                 if (shaHex.length() < 2) {
543                     hexString.append(0);
544                 }
545                 hexString.append(shaHex);
546             }
547             return hexString.toString();
548         } catch (NoSuchAlgorithmException e) {
549             e.printStackTrace();
550         }
551         return "";
552     }
553
554
555     public static String getLocalIP() {
556         InetAddress addr = null;
557         try {
558             addr = InetAddress.getLocalHost();
559         } catch (UnknownHostException e) {
560             e.printStackTrace();
561         }
562
563         byte[] ipAddr = addr.getAddress();
564         String ipAddrStr = "";
565         for (int i = 0; i < ipAddr.length; i++) {
566             if (i > 0) {
567                 ipAddrStr += ".";
568             }
569             ipAddrStr += ipAddr[i] & 0xFF;
570         }
571         // System.out.println("i am ip:......"+ipAddrStr);
572         return ipAddrStr;
573     }
574
575     /**随机生成字符串(0-9)
576       * 
577       * @param lengthCount 长度
578       * @return
579       */
580     public static String generateCardNo(Integer lengthCount) {
581          if(!SimpleTool.checkNotNull(lengthCount)) {
582              lengthCount = 6;
583          }
584          java.util.Random r=new java.util.Random();
585          StringBuilder str = new StringBuilder();//定义变长字符串
586          for(int i=0;i<lengthCount;i++){
587              str.append(r.nextInt(10));
588          }
589          return str.toString();
590      }
591
592      /**判断是不是视频文件
593       * @param fileName 文件名称
594       * @return boolean true是视频文件
595       */
596     public static boolean getMimeType(String fileName) {  
597          boolean b = false;
598         FileNameMap fileNameMap = URLConnection.getFileNameMap();  
599         String type = fileNameMap.getContentTypeFor(fileName);  
600         //是视频type是为空的
601         if(!checkNotNull(type)) {
602             b = true;
603         }
604         return b;  
605      } 
606     
607     /**
608      * 判断是否为视频
609      * @param fileName
610      * @return
611      */
612     public static String isVideo(String fileName) {  
613         FileNameMap fileNameMap = URLConnection.getFileNameMap();  
614         String type = fileNameMap.getContentTypeFor(fileName);  
615         return type;  
616     }
617  
618     /**判断是否是中文*/
619     public static boolean isChineseChar(String str){        
620         boolean temp = false;        
621         Pattern p=Pattern.compile("[\u4e00-\u9fa5]");        
622         Matcher m=p.matcher(str);        
623         if(m.find()){            
624             temp =  true;        
625             }        
626         return temp;    
627     }
628     
629     /**去除字符串中不是中文的字符
630      * 
631      */
632     public static String deleteNoChinese(String str){
633         String name="";
634         if(checkNotNull(str)){
635             for(int i=0;i<str.length();i++){
636                 String s = str.substring(i, i+1);
637                 if(isChineseChar(s)){
638                     name = name +s;
639                 }
640             }
641         }
642         return name;
643     }
644    
645     /**生成字母(全部是中文的)*/
646     public static String convertHanzi3Pinyin(String hanzi,boolean full){
647         hanzi = deleteNoChinese(hanzi);
648         hanzi = convertHanzi2Pinyin(hanzi,false);
649         return hanzi;
650     }
651     
652     /***获取字符串拼音的第一个字母(大写)**/
653     public static String convertStringPinyinOne(String hanzi) {
654         if(SimpleTool.checkNotNull(hanzi)) {
655             //转化为便宜
656             hanzi = convertHanzi2Pinyin(hanzi,false);
657             //转化大写
658             hanzi = hanzi.toUpperCase();
659             /*//获取第一个
660             byte[] datas = hanzi.getBytes();
661             if(datas.length>0) {
662                 byte[] datas2 = new byte[] {datas[0]};
663                 hanzi = new String(datas2);
664             }else {
665                 hanzi = "";
666             }*/
667         }
668         return hanzi;
669     }
670     
671     
672     /***将汉字转成拼音(取首字母或全拼)
673      * @param hanzi
674      * @param full 是否全拼
675      * @return
676      */
677     public static String convertHanzi2Pinyin(String hanzi,boolean full){
678         //获取第一个字
679        /* if(checkNotNull(hanzi)){
680             boolean isHave = true;
681             Integer l = hanzi.length();
682             Integer index = 0;
683             while (isHave) {
684                 String hanzi2 = hanzi.substring(index,index+1);
685                 if(isChineseChar(hanzi2)){
686                     isHave = false;
687                     hanzi = hanzi2;
688                 }else{
689                     if(index<l-1){
690                         index++;
691                     }else{
692                         isHave = false;
693                     }
694                 }
695             }
696         }
697         */
698         //去除所有的空格
699         if(checkNotNull(hanzi)){
700             hanzi = hanzi.replaceAll(" ", "");
701         }
702     
703         /***
704         * ^[\u2E80-\u9FFF]+$ 匹配所有东亚区的语言 
705         * ^[\u4E00-\u9FFF]+$ 匹配简体和繁体 
706         * ^[\u4E00-\u9FA5]+$ 匹配简体
707         */
708         String regExp="^[\u4E00-\u9FFF]+$";
709         StringBuffer sb=new StringBuffer();
710         if(hanzi==null||"".equals(hanzi.trim())){
711             return "";
712         }
713         String pinyin="";
714         for(int i=0;i<hanzi.length();i++){
715             char unit=hanzi.charAt(i);
716             if(match(String.valueOf(unit),regExp)){//是汉字,则转拼音
717                 pinyin=convertSingleHanzi2Pinyin(unit);
718                 if(full){
719                     sb.append(pinyin);
720                 }else{
721                     sb.append(pinyin.charAt(0));
722                 }
723             }else{
724                 sb.append(unit);
725             }
726         }
727         return sb.toString();
728     }
729     
730     /***将单个汉字转成拼音
731      * @param hanzi
732      * @return
733      */
734     private static String convertSingleHanzi2Pinyin(char hanzi){
735          HanyuPinyinOutputFormat outputFormat = new HanyuPinyinOutputFormat();
736          outputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
737          String[] res;
738          StringBuffer sb=new StringBuffer();
739          try {
740              res = PinyinHelper.toHanyuPinyinStringArray(hanzi,outputFormat);
741              sb.append(res[0]);//对于多音字,只用第一个拼音
742          } catch (Exception e) {
743              e.printStackTrace();
744              return "";
745          }
746          return sb.toString();
747      }
748     
749     /***@param str 源字符串
750       * @param regex 正则表达式
751       * @return 是否匹配
752       */
753     public static boolean match(String str,String regex){
754         Pattern pattern=Pattern.compile(regex);
755           Matcher matcher=pattern.matcher(str);
756           return matcher.find();
757       }
758     
759     /** 读取 Excel文件内容(3.24 quan)
760      * 
761      * @param excel_name  File
762      * @return
763      * @throws Exception
764      */
765     public static List<String[]> readExcelByeFile2(File excel_name) throws Exception {
766         // 结果集
767         List<String[]> list = new ArrayList<String[]>();
768         HSSFWorkbook hssfworkbook = new HSSFWorkbook(new FileInputStream(excel_name));
769
770         // 遍历该表格中所有的工作表,i表示工作表的数量 getNumberOfSheets表示工作表的总数
771         HSSFSheet hssfsheet = hssfworkbook.getSheetAt(0);
772
773         // 遍历该行所有的行,j表示行数 getPhysicalNumberOfRows行的总数
774         for (int j = 0; j < hssfsheet.getPhysicalNumberOfRows(); j++) {
775             HSSFRow hssfrow = hssfsheet.getRow(j);
776             if(hssfrow!=null){
777             int col = hssfrow.getPhysicalNumberOfCells();
778             // 单行数据
779             String[] arrayString = new String[col];
780             for (int i = 0; i < col; i++) {
781                 HSSFCell cell = hssfrow.getCell(i);
782                 if (cell == null) {
783                     arrayString[i] = "";
784                 } else if (cell.getCellType() == 0) {
785                     // arrayString[i] = new Double(cell.getNumericCellValue()).toString();
786                      short format = cell.getCellStyle().getDataFormat();  
787                         SimpleDateFormat sdf = null;  
788                         if(format == 14 || format == 31 || format == 57 || format == 58){  
789                             //日期  
790                             sdf = new SimpleDateFormat("yyyy-MM-dd");  
791                         }else if (format == 20 || format == 32) {  
792                             //时间  
793                             sdf = new SimpleDateFormat("HH:mm");  
794                         }else if (HSSFCell.CELL_TYPE_NUMERIC == cell.getCellType()) { 
795                           if (HSSFDateUtil.isCellDateFormatted(cell)) {    
796                             Date d = cell.getDateCellValue();    
797                             DateFormat formater = new SimpleDateFormat("yyyy年"); 
798                             // DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
799                             arrayString[i] = formater.format(d);   
800                            } else {
801                                arrayString[i] = new BigDecimal(cell.getNumericCellValue()).toString();    
802                         }
803                     }
804                 } else {// 如果EXCEL表格中的数据类型为字符串型
805                     arrayString[i] = cell.getStringCellValue().trim();
806                 }
807             }
808             list.add(arrayString);
809         }
810         }
811         return list;
812     }
813     
814     /**
815      * 读取 Excel文件内容
816      * 
817      * @param excel_name
818      * @param header 是否包括表头
819      * @return
820      * @throws Exception
821      */
822     public static List<String[]> readExcelByeFileData(File excel_name,boolean header) throws Exception {
823         // 结果集
824         List<String[]> list = new ArrayList<String[]>();
825         
826         HSSFWorkbook hssfworkbook = new HSSFWorkbook(new FileInputStream(
827                 excel_name));
828         
829         // 遍历该表格中所有的工作表,i表示工作表的数量 getNumberOfSheets表示工作表的总数
830         for(int s=0;s<hssfworkbook.getNumberOfSheets();s++) {
831             HSSFSheet hssfsheet = hssfworkbook.getSheetAt(s);
832             int col = 0;
833             // 遍历该行所有的行,j表示行数 getPhysicalNumberOfRows行的总数 去除标题
834             for (int j = 0; j < hssfsheet.getPhysicalNumberOfRows(); j++) {
835                 HSSFRow hssfrow = hssfsheet.getRow(j);
836                 if(hssfrow!=null){
837                     if(j == 0) {
838                         col = hssfrow.getPhysicalNumberOfCells();
839                         if(!header) {
840                             //不包括表头
841                             continue;
842                         }
843                     }
844                     // 单行数据
845                     String[] arrayString = new String[col];
846                     for (int i = 0; i < col; i++) {
847                         HSSFCell cell = hssfrow.getCell(i);
848                         if (cell == null) {
849                             arrayString[i] = "";
850                         } else if (cell.getCellType() == 0) {
851                             // arrayString[i] = new Double(cell.getNumericCellValue()).toString();
852                             if (HSSFCell.CELL_TYPE_NUMERIC == cell.getCellType()) {
853                                 short format = cell.getCellStyle().getDataFormat();  
854                                 if(format == 14 || format == 31 || format == 57 || format == 58){  
855                                     //日期(中文时间格式的)
856                                     Date d = cell.getDateCellValue();    
857                                     DateFormat formater = new SimpleDateFormat("yyyy年");    
858                                     // DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
859                                     arrayString[i] = formater.format(d);   
860                                 }else if (HSSFDateUtil.isCellDateFormatted(cell)) {    
861                                     Date d = cell.getDateCellValue();    
862                                     DateFormat formater = new SimpleDateFormat("yyyy年");    
863                                     // DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
864                                     arrayString[i] = formater.format(d);   
865                                 } else {    
866                                     if(HSSFCell.CELL_TYPE_STRING == cell.getCellType()){
867                                         arrayString[i] =cell.getStringCellValue();
868                                     }else if(HSSFCell.CELL_TYPE_FORMULA==cell.getCellType()){
869                                         arrayString[i] =cell.getCellFormula();
870                                     }else if(HSSFCell.CELL_TYPE_NUMERIC== cell.getCellType()){
871                                         HSSFDataFormatter dataFormatter = new HSSFDataFormatter();
872                                         arrayString[i] =dataFormatter.formatCellValue(cell);
873                                     }
874                                 }
875                             }
876                         } else if(cell.getCellType() == Cell.CELL_TYPE_BLANK){
877                             arrayString[i] = "";
878                         } else { // 如果EXCEL表格中的数据类型为字符串型
879                             arrayString[i] = cell.getStringCellValue().trim();
880                         }
881                     }
882                     list.add(arrayString);
883                 }
884             }
885         }
886         return list;
887     }
888     
889     /**
890      * 读取 Excel文件内容(学校信息专用)
891      * 
892      * @param excel_name
893      * @return
894      * @throws Exception
895      */
896     public static List<String[]> readExcelByeFile(File excel_name) throws Exception {
897         // 结果集
898         List<String[]> list = new ArrayList<String[]>();
899
900         HSSFWorkbook hssfworkbook = new HSSFWorkbook(new FileInputStream(
901                 excel_name));
902
903         // 遍历该表格中所有的工作表,i表示工作表的数量 getNumberOfSheets表示工作表的总数
904         for(int s=0;s<hssfworkbook.getNumberOfSheets();s++) {
905             HSSFSheet hssfsheet = hssfworkbook.getSheetAt(s);
906             int col = 0;
907             // 遍历该行所有的行,j表示行数 getPhysicalNumberOfRows行的总数 去除标题
908             for (int j = 0; j < hssfsheet.getPhysicalNumberOfRows(); j++) {
909                 HSSFRow hssfrow = hssfsheet.getRow(j);
910                 if(hssfrow!=null){
911                     if(j == 0) {
912                         col = hssfrow.getPhysicalNumberOfCells();
913                     }else {
914                         //                int col = hssfrow.getPhysicalNumberOfCells();
915                         // 单行数据
916                         String[] arrayString = new String[col];
917                         for (int i = 0; i < col; i++) {
918                             HSSFCell cell = hssfrow.getCell(i);
919                             if (cell == null) {
920                                 arrayString[i] = "";
921                             } else if (cell.getCellType() == 0) {
922                                 // arrayString[i] = new Double(cell.getNumericCellValue()).toString();
923                                 if (HSSFCell.CELL_TYPE_NUMERIC == cell.getCellType()) {
924                                     short format = cell.getCellStyle().getDataFormat();  
925                                     if(format == 14 || format == 31 || format == 57 || format == 58){  
926                                         //日期(中文时间格式的)
927                                         Date d = cell.getDateCellValue();    
928                                         DateFormat formater = new SimpleDateFormat("yyyy年");    
929                                         // DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
930                                         arrayString[i] = formater.format(d);   
931                                     }else if (HSSFDateUtil.isCellDateFormatted(cell)) {    
932                                         Date d = cell.getDateCellValue();    
933                                         DateFormat formater = new SimpleDateFormat("yyyy年");    
934                                         // DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
935                                         arrayString[i] = formater.format(d);   
936                                     } else {    
937                                         if(HSSFCell.CELL_TYPE_STRING == cell.getCellType()){
938                                             arrayString[i] =cell.getStringCellValue();
939                                         }else if(HSSFCell.CELL_TYPE_FORMULA==cell.getCellType()){
940                                             arrayString[i] =cell.getCellFormula();
941                                         }else if(HSSFCell.CELL_TYPE_NUMERIC== cell.getCellType()){
942                                             HSSFDataFormatter dataFormatter = new HSSFDataFormatter();
943                                             arrayString[i] =dataFormatter.formatCellValue(cell);
944                                         }
945                                     }
946                                 }
947                             } else if(cell.getCellType() == Cell.CELL_TYPE_BLANK){
948                                 arrayString[i] = "";
949                             } else { // 如果EXCEL表格中的数据类型为字符串型
950                                 cell.setCellType(Cell.CELL_TYPE_STRING);
951                                 String name = cell.getStringCellValue().trim();
952                                 if(name.equals("-")) {
953                                     arrayString[i] = "";
954                                 }else {
955                                     arrayString[i] = name;
956                                 }
957                             }
958                         }
959                         list.add(arrayString);
960                     }
961                 }
962             }
963         }
964         return list;
965     }
966     
967     /**获取字符串里面的数字,按顺序排序*/
968     public static String stringNumber(String data) {
969         String da = null;
970         String regEc = "[^0-9]";
971         Pattern pattern = Pattern.compile(regEc);
972         Matcher m = pattern.matcher(data);
973         da = m.replaceAll("").trim();
974         return da;
975     }
976     
977      /** 
978      * @param url:请求url 
979      * @param content: 请求体(参数) 
980      * @return errorStr:错误信息;status:状态码,response:返回数据 
981      * @throws JSONException 
982      */  
983     public static JSONObject requestData(String url, String content) throws JSONException {  
984         JSONObject obj = new JSONObject();
985         String errMsg_r = "";  
986         String status_r = "0";  
987         String response = "";
988         //PrintWriter out = null;  
989         DataOutputStream out = null;
990         BufferedReader in = null;
991         try {  
992             URL realUrl = new URL(url);  
993             // 打开和URL之间的连接  
994             URLConnection conn = realUrl.openConnection();  
995             HttpURLConnection httpUrlConnection = (HttpURLConnection) conn;  
996             // 设置请求属性  
997             httpUrlConnection.setRequestProperty("Content-type", "application/json;charset=UTF-8");
998             //httpUrlConnection.setRequestProperty("Content-Type", "application/json");  
999             //httpUrlConnection.setRequestProperty("Charset", "UTF-8");
1000             httpUrlConnection.setRequestProperty("x-adviewrtb-version", "2.1");  
1001             // 发送POST请求必须设置如下两行  
1002             httpUrlConnection.setDoOutput(true);  
1003             httpUrlConnection.setDoInput(true);  
1004             // 获取URLConnection对象对应的输出流  
1005             out = new DataOutputStream(httpUrlConnection.getOutputStream());
1006             //out = new PrintWriter(httpUrlConnection.getOutputStream());  
1007             // 发送请求参数  
1008             //out.write(content);
1009             out.write(content.getBytes("UTF-8"));
1010             // flush输出流的缓冲 
1011             out.flush();  
1012             httpUrlConnection.connect();  
1013             // 定义BufferedReader输入流来读取URL的响应  
1014             // in = new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream()));  
1015             String wxMsgXml = IOUtils.toString(httpUrlConnection.getInputStream(), "utf-8");
1016             System.out.println("wxMsgXml:"+wxMsgXml);
1017            if(SimpleTool.checkNotNull(wxMsgXml)) {
1018                obj = JSONObject.fromObject(wxMsgXml);
1019            }
1020            /* String line;  
1021             while ((line = in.readLine()) != null) {  
1022                 response += line;  
1023             }  */
1024             status_r = new Integer(httpUrlConnection.getResponseCode()).toString();  
1025         } catch (Exception e) {  
1026             System.out.println("发送 POST 请求出现异常!" + e);  
1027             errMsg_r = e.getMessage();  
1028             e.printStackTrace();
1029         }  
1030         // 使用finally块来关闭输出流、输入流  
1031         finally {  
1032             try {  
1033                 if (out != null) { out.close();}  
1034                 if (in != null) {in.close();}  
1035             } catch (Exception ex) {  
1036                 ex.printStackTrace();  
1037             }  
1038         }  
1039         obj.put("errMsg_r", errMsg_r);  
1040         obj.put("status_r", status_r);  
1041         return obj;  
1042     }  
1043     
1044     /**随机生成字数(整数)(包括 0)
1045       * @param maxNumber 最大值
1046       * @return
1047       */
1048     public static Integer randomData(Integer maxNumber) {
1049          java.util.Random r=new java.util.Random();
1050          return r.nextInt(maxNumber);
1051      }
1052     
1053       private static final String[] HEADERS_TO_TRY = {"X-Forwarded-For", "Proxy-Client-IP", "WL-Proxy-Client-IP",
1054                 "HTTP_X_FORWARDED_FOR", "HTTP_X_FORWARDED", "HTTP_X_CLUSTER_CLIENT_IP", "HTTP_CLIENT_IP",
1055                 "HTTP_FORWARDED_FOR", "HTTP_FORWARDED", "HTTP_VIA", "REMOTE_ADDR", "X-Real-IP"};
1056
1057         /**
1058          * getClientIpAddress:(获取用户ip,可穿透代理). <br/>
1059          * @param request
1060          * @return
1061          * @author chenjiahe
1062          * @Date 2018年3月2日下午4:41:47
1063          * @since JDK 1.7
1064          */
1065         public static String getClientIpAddress(HttpServletRequest request) {
1066             for (String header : HEADERS_TO_TRY) {
1067                 String ip = request.getHeader(header);
1068                 if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
1069                     return ip;
1070                 }
1071             }
1072             return request.getRemoteAddr();
1073         }
1074     
1075 }