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