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