package com.hx.util;
|
|
import java.io.BufferedReader;
|
import java.io.DataOutputStream;
|
import java.io.File;
|
import java.io.FileInputStream;
|
import java.io.IOException;
|
import java.io.UnsupportedEncodingException;
|
import java.math.BigDecimal;
|
import java.math.RoundingMode;
|
import java.net.FileNameMap;
|
import java.net.HttpURLConnection;
|
import java.net.InetAddress;
|
import java.net.URL;
|
import java.net.URLConnection;
|
import java.net.URLDecoder;
|
import java.net.UnknownHostException;
|
import java.security.MessageDigest;
|
import java.security.NoSuchAlgorithmException;
|
import java.sql.Timestamp;
|
import java.text.DateFormat;
|
import java.text.DecimalFormat;
|
import java.text.ParseException;
|
import java.text.SimpleDateFormat;
|
import java.util.*;
|
import java.util.regex.Matcher;
|
import java.util.regex.Pattern;
|
|
import javax.servlet.http.HttpServletRequest;
|
|
import org.apache.commons.io.IOUtils;
|
import org.apache.poi.hssf.usermodel.HSSFCell;
|
import org.apache.poi.hssf.usermodel.HSSFDataFormatter;
|
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
|
import org.apache.poi.hssf.usermodel.HSSFRow;
|
import org.apache.poi.hssf.usermodel.HSSFSheet;
|
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
|
import org.apache.poi.ss.usermodel.Cell;
|
|
import net.sf.json.JSONArray;
|
import net.sf.json.JSONException;
|
import net.sf.json.JSONObject;
|
import net.sourceforge.pinyin4j.PinyinHelper;
|
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
|
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
|
import org.apache.poi.ss.usermodel.CellType;
|
import org.springframework.cglib.beans.BeanMap;
|
|
public class SimpleTool {
|
|
public static SimpleDateFormat myformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
public static DecimalFormat fmt = new DecimalFormat("0.00");
|
public static Byte[] lock = new Byte[] {0};
|
|
/**对象转map*/
|
public static Map<?, ?> objectToMap(Object obj) {
|
if(obj == null)
|
return null;
|
|
return new org.apache.commons.beanutils.BeanMap(obj);
|
}
|
|
/**
|
* 将对象装换为map
|
*
|
* @param bean
|
* @return
|
*/
|
public static <T> Map<String, Object> beanToMap(T bean) {
|
Map<String, Object> map = new HashMap<>();
|
if (bean != null) {
|
BeanMap beanMap = BeanMap.create(bean);
|
for (Object key : beanMap.keySet()) {
|
map.put(key + "", beanMap.get(key));
|
}
|
}
|
return map;
|
}
|
|
/**
|
* 将对象装换为map
|
*
|
* @param bean
|
* @return
|
*/
|
public static Map<String, String> beanToMapS(Object bean) {
|
Map<String, String> map = new HashMap<>();
|
if (bean != null) {
|
BeanMap beanMap = BeanMap.create(bean);
|
for (Object key : beanMap.keySet()) {
|
if(beanMap.get(key) != null){
|
map.put(key + "", beanMap.get(key).toString());
|
}else{
|
map.put(key + "", "");
|
}
|
}
|
}
|
return map;
|
}
|
|
|
/**
|
* 后台格式构建返回值格式列表-后台获取列表
|
* @param count 返回总条数
|
* @return JSONObject 特定格式的JSONObject
|
*/
|
public static JSONObject resAdminLsit(Integer status,String errMsg,JSONArray arr,Integer count){
|
|
JSONObject fObj = new JSONObject();
|
try{
|
fObj.put("code", status);
|
fObj.put("count", count);
|
fObj.put("msg", errMsg);
|
fObj.put("data", arr);
|
}catch (Exception e) {
|
e.printStackTrace();
|
}
|
return fObj;
|
}
|
|
/**
|
* 获取指定格式的Double 类型数据
|
*
|
* @param type
|
* 转换格式的类型 默认为 "#.#"
|
* @param e
|
* 要转换的数据源
|
**/
|
public static Double getTypeDouble(String type, Double e) {
|
if (!checkNotNull(type))
|
type = "0.00";
|
fmt = new DecimalFormat(type);
|
fmt.setRoundingMode(RoundingMode.HALF_UP); // 保留小数点后两位并四舍五入,确保价钱准确
|
Double d = Double.valueOf(fmt.format(e));
|
return d;
|
}
|
|
/**
|
* 首字母大写
|
*
|
* @param str
|
*/
|
public static String capitalized(String str) {
|
if ("".equals(str.trim()) || str == null) {
|
return "";
|
}
|
String key = str.substring(0, 1).toUpperCase();
|
String keys = key + str.substring(1, str.length());
|
return keys;
|
}
|
|
/** 判断参数是否为null,如果null抛出对应异常 */
|
public static void checkErrMsg(Object obj, String errMsg) {
|
if (!checkNotNull(obj))
|
throw new RuntimeException(errMsg);
|
}
|
|
/*** 创建文件(自动生成文件夹。)(需要真实路径) **/
|
public static File createFile(String mkdirPath, String fileName) throws IOException {
|
System.out.println(mkdirPath + fileName);
|
// mkdirPath =
|
// "E:\\work\\soft\\MyEclipse\\apache-tomcat-7.0.61\\webapps\\ROOT\\";
|
|
File f = new File(mkdirPath);
|
if (!f.exists()) {
|
f.mkdirs();
|
}
|
File file = new File(f, fileName);
|
if (!file.exists()) {
|
file.createNewFile();
|
}
|
|
// System.out.println(file.getAbsolutePath());
|
return file;
|
}
|
|
/**
|
* 构建返回值格式
|
*
|
* @param status
|
* 返回状态
|
* @param errMsg
|
* 返回附带信息
|
* @param inf
|
* 返回实体值
|
* @return JSONObject 特定格式的JSONObject
|
*/
|
public static JSONObject res(Integer status, String errMsg, JSONObject inf) {
|
JSONObject res = new JSONObject();
|
JSONObject fObj = new JSONObject();
|
try {
|
res.put("status", status);
|
res.put("errMsg", errMsg);
|
|
fObj.put("res", res);
|
fObj.put("inf", inf);
|
} catch (Exception e) {
|
e.printStackTrace();
|
}
|
return fObj;
|
}
|
|
/**
|
* Date类型转换为10位时间戳
|
*
|
* @param time
|
* @return
|
*/
|
public static Integer DateToTimestamp(Date time) {
|
Timestamp ts = new Timestamp(time.getTime());
|
return (int) ((ts.getTime()) / 1000);
|
}
|
|
/** 判断当前时间是什么时候 **/
|
public static Boolean IsTime(Date date, Integer year, Integer month, Integer day, Integer hour, Integer minute) {
|
Calendar cal = new GregorianCalendar();
|
cal.setTime(date);
|
if (year != null) {
|
int iyear = cal.get(Calendar.YEAR);
|
if (iyear != year)
|
return false;
|
}
|
|
if (month != null) {
|
int imonth = cal.get(Calendar.MONTH);// 获取月份(月份从0开始计算的)
|
imonth = imonth + 1;
|
if (imonth != month)
|
return false;
|
}
|
|
if (day != null) {
|
int iday = cal.get(Calendar.DATE);// 获取日
|
if (iday != day)
|
return false;
|
}
|
|
if (hour != null) {
|
int ihour = cal.get(Calendar.HOUR_OF_DAY);// 24小时 0- 23
|
if (ihour != hour)
|
return false;
|
}
|
|
if (minute != null) {
|
int iminute = cal.get(Calendar.MINUTE);
|
if (iminute != minute)
|
return false;
|
}
|
// Boolean b = yearTag && monthTag && dayTag && hourTag && minuteTag;
|
return true;
|
}
|
|
/**
|
* 根据具体时间属性判断是否相同
|
*
|
*/
|
public static Boolean DateEquals(Date date1, Date date2, Boolean year, Boolean month, Boolean day, Boolean hour,
|
Boolean minute) {
|
|
Calendar calendar1 = new GregorianCalendar();
|
Calendar calendar2 = new GregorianCalendar();
|
calendar1.setTime(date1);
|
calendar2.setTime(date2);
|
|
if (year) {
|
if (calendar1.get(Calendar.YEAR) != calendar2.get(Calendar.YEAR)) {
|
return false;
|
}
|
}
|
if (month) {
|
if (calendar1.get(Calendar.MONTH) != calendar2.get(Calendar.MONTH)) {
|
return false;
|
}
|
}
|
if (day) {
|
if (calendar1.get(Calendar.DATE) != calendar2.get(Calendar.DATE)) {
|
return false;
|
}
|
}
|
if (year) {
|
if (calendar1.get(Calendar.HOUR_OF_DAY) != calendar2.get(Calendar.HOUR_OF_DAY)) {
|
return false;
|
}
|
}
|
if (year) {
|
if (calendar1.get(Calendar.MINUTE) != calendar2.get(Calendar.MINUTE)) {
|
return false;
|
}
|
}
|
|
// Boolean b = yearTag && monthTag && dayTag && hourTag && minuteTag;
|
|
return true;
|
}
|
|
/** 获取10位数时间戳 */
|
public static Integer getTenTime(Date date) {
|
Timestamp ts = new Timestamp(date.getTime());
|
return (int) ((ts.getTime()) / 1000);
|
}
|
|
/**
|
* 获取指定日期的明天 difDay 把日期往后增加一天.整数往后推,负数往前移动
|
*
|
* @return date
|
*/
|
@SuppressWarnings("static-access")
|
public static Date getDetailDay(Date today, int difDay) {
|
Calendar calendar = new GregorianCalendar();
|
calendar.setTime(today);
|
calendar.add(calendar.DATE, difDay);// 把日期往后增加一天.整数往后推,负数往前移动
|
Date d = calendar.getTime();
|
return d;
|
}
|
|
/**
|
* 获取想要的格式的时间
|
*
|
* @return String
|
*/
|
public static String getTypeDate(String type, Date date) {
|
if (date == null)
|
return null;
|
|
if (SimpleTool.checkNotNull(type)) {
|
myformat = new SimpleDateFormat(type);
|
String returnDate = myformat.format(date);
|
myformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
return returnDate;
|
} else {
|
String returnDate = myformat.format(date);
|
return returnDate;
|
}
|
|
}
|
|
/**
|
* 比较两个时间天数差 startTime - endTime
|
*
|
* @param type
|
* (无效)
|
* @return String
|
* @throws ParseException
|
*/
|
public static int getDiffDate(String type, Date startTime, Date endTime) throws ParseException {
|
type = "yyyyMMdd";
|
SimpleDateFormat myformat = new SimpleDateFormat(type);
|
int i = 0;
|
i = (int) ((myformat.parse(myformat.format(startTime)).getTime()
|
- myformat.parse(myformat.format(endTime)).getTime()) / (1000 * 60 * 60 * 24));
|
// return
|
// myformat.parse(myformat.format(date1)).compareTo(myformat.parse(myformat.format(date2)));
|
return i;
|
}
|
|
/**
|
* 得到两个时间的分钟差 date1 - date2 这个是个奇葩。但是整型了。
|
*
|
* @return int
|
* @throws ParseException
|
*/
|
public static int getLeftDateForMinue(Date date1, Date date2) throws ParseException {
|
long times = date1.getTime() - date2.getTime();
|
times = times / (1000 * 60);
|
return (int) times;
|
}
|
|
/**把字符串转为特定时间格式
|
*
|
* @param type 时间格式
|
* @param sDate 字符串时间(可以为空)
|
* @return date
|
* @throws ParseException
|
*/
|
public static Date parseStringForDate(String type, String sDate){
|
Date date = null;
|
try {
|
if(SimpleTool.checkNotNull(sDate)) {
|
SimpleDateFormat myformat = new SimpleDateFormat(type);
|
date = myformat.parse(sDate);
|
}
|
} catch (Exception e) {
|
e.printStackTrace();
|
}
|
return date;
|
}
|
|
/**
|
* 判断是否为空
|
*/
|
public static boolean checkNotNull(Object o) {
|
boolean b = false;
|
if (o != null && !"".equals(o)&&!"undefined".equals(o)&&!" ".equals(o)) {
|
b = true;
|
}
|
return b;
|
}
|
|
/**
|
* 判断是否为空 (多个)
|
*/
|
public static boolean checkNotNullM(Object[] os) {
|
boolean b = true;
|
for (Object o : os) {
|
if (o == null || "".equals(o))
|
return false;
|
}
|
return b;
|
}
|
|
/**
|
* 获取服务器端的webapps路径
|
*
|
* @return
|
*/
|
public String findServerPath() {
|
String classPath = this.getClass().getClassLoader().getResource("/").getPath();
|
try {
|
classPath = URLDecoder.decode(classPath, "gb2312");
|
} catch (UnsupportedEncodingException e) {
|
e.printStackTrace();
|
}
|
String[] strPath = classPath.split("/");
|
String path = "";
|
for (int i = 0; i < strPath.length; i++) {
|
if (i > 0 && i <= 3) {
|
path = path + strPath[i] + "/";
|
}
|
}
|
return path;
|
}
|
|
/**
|
* 删除文件 输入真是路径
|
*/
|
public static void deleteFile(String sPath) {
|
File file = new File(sPath);
|
// 判断目录或文件是否存在
|
if (file.exists()) {
|
// 判断是否为文件
|
if (file.isFile()) { // 为文件时调用删除文件方法
|
deleteFileForOne(sPath);
|
} else { // 为目录时调用删除目录方法
|
throw new RuntimeException("dir is no del");
|
// deleteDirectory(sPath);
|
}
|
}
|
}
|
|
/**
|
* 删除目录(文件夹)以及目录下的文件
|
*
|
* @param sPath
|
* 被删除目录的文件路径
|
* @return 目录删除成功返回true,否则返回false
|
*/
|
public static boolean deleteDirectory(String sPath) {
|
// 如果sPath不以文件分隔符结尾,自动添加文件分隔符
|
if (!sPath.endsWith(File.separator)) {
|
sPath = sPath + File.separator;
|
}
|
File dirFile = new File(sPath);
|
// 如果dir对应的文件不存在,或者不是一个目录,则退出
|
if (!dirFile.exists() || !dirFile.isDirectory()) {
|
return false;
|
}
|
Boolean flag = true;
|
// 删除文件夹下的所有文件(包括子目录)
|
File[] files = dirFile.listFiles();
|
for (int i = 0; i < files.length; i++) {
|
// 删除子文件
|
if (files[i].isFile()) {
|
flag = deleteFileForOne(files[i].getAbsolutePath());
|
if (!flag)
|
break;
|
} // 删除子目录
|
else {
|
flag = deleteDirectory(files[i].getAbsolutePath());
|
if (!flag)
|
break;
|
}
|
}
|
if (!flag)
|
return false;
|
// 删除当前目录
|
if (dirFile.delete()) {
|
return true;
|
} else {
|
return false;
|
}
|
}
|
|
/**
|
* 删除单个文件
|
*
|
* @param sPath
|
* 被删除文件的文件名
|
* @return 单个文件删除成功返回true,否则返回false
|
*/
|
public static boolean deleteFileForOne(String sPath) {
|
Boolean flag = false;
|
File file = new File(sPath);
|
// 路径为文件且不为空则进行删除
|
if (file.isFile() && file.exists()) {
|
file.delete();
|
flag = true;
|
}
|
return flag;
|
}
|
|
|
/**
|
* 获取uuid
|
*/
|
public static String getUUIDName() {
|
return UUID.randomUUID().toString();
|
}
|
|
|
/** 获取异常信息 **/
|
public static String getExceptionMsg(Exception e) {
|
StringBuffer emsg = new StringBuffer();
|
if (e != null) {
|
StackTraceElement[] st = e.getStackTrace();
|
for (StackTraceElement stackTraceElement : st) {
|
String exclass = stackTraceElement.getClassName();
|
String method = stackTraceElement.getMethodName();
|
emsg.append("[类:" + exclass + "]调用---" + method + "----时在第" + stackTraceElement.getLineNumber()
|
+ "行代码处发生异常!异常类型:" + e.toString() + "(" + e.getMessage() + ")\r\n");
|
}
|
}
|
return emsg.toString();
|
}
|
|
/**
|
* 获取指定格式的Double 类型数据
|
*
|
* 转换格式的类型 默认为 "#.##"
|
* @param e
|
* 要转换的数据源
|
**/
|
public static Double getTypeDouble(Double e) {
|
fmt.setRoundingMode(RoundingMode.HALF_UP); // 保留小数点后两位并四舍五入,确保价钱准确
|
Double d = Double.valueOf(fmt.format(e));
|
return d;
|
}
|
|
|
/**
|
* SHA1 加密
|
*
|
* @param decript
|
* @return
|
*/
|
public static String SHA1(String decript) {
|
try {
|
MessageDigest digest = MessageDigest.getInstance("SHA-1");
|
digest.update(decript.getBytes());
|
byte messageDigest[] = digest.digest();
|
// Create Hex String
|
StringBuffer hexString = new StringBuffer();
|
// 字节数组转换为 十六进制 数
|
for (int i = 0; i < messageDigest.length; i++) {
|
String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
|
if (shaHex.length() < 2) {
|
hexString.append(0);
|
}
|
hexString.append(shaHex);
|
}
|
return hexString.toString();
|
} catch (NoSuchAlgorithmException e) {
|
e.printStackTrace();
|
}
|
return "";
|
}
|
|
|
public static String getLocalIP() {
|
InetAddress addr = null;
|
try {
|
addr = InetAddress.getLocalHost();
|
} catch (UnknownHostException e) {
|
e.printStackTrace();
|
}
|
|
byte[] ipAddr = addr.getAddress();
|
String ipAddrStr = "";
|
for (int i = 0; i < ipAddr.length; i++) {
|
if (i > 0) {
|
ipAddrStr += ".";
|
}
|
ipAddrStr += ipAddr[i] & 0xFF;
|
}
|
// System.out.println("i am ip:......"+ipAddrStr);
|
return ipAddrStr;
|
}
|
|
/**随机生成字符串(0-9)
|
*
|
* @param lengthCount 长度
|
* @return
|
*/
|
public static String generateCardNo(Integer lengthCount) {
|
if(!SimpleTool.checkNotNull(lengthCount)) {
|
lengthCount = 6;
|
}
|
java.util.Random r=new java.util.Random();
|
StringBuilder str = new StringBuilder();//定义变长字符串
|
for(int i=0;i<lengthCount;i++){
|
str.append(r.nextInt(10));
|
}
|
return str.toString();
|
}
|
|
/**判断是不是视频文件
|
* @param fileName 文件名称
|
* @return boolean true是视频文件
|
*/
|
public static boolean getMimeType(String fileName) {
|
boolean b = false;
|
FileNameMap fileNameMap = URLConnection.getFileNameMap();
|
String type = fileNameMap.getContentTypeFor(fileName);
|
//是视频type是为空的
|
if(!checkNotNull(type)) {
|
b = true;
|
}
|
return b;
|
}
|
|
/**
|
* 判断是否为视频
|
* @param fileName
|
* @return
|
*/
|
public static String isVideo(String fileName) {
|
FileNameMap fileNameMap = URLConnection.getFileNameMap();
|
String type = fileNameMap.getContentTypeFor(fileName);
|
return type;
|
}
|
|
/**判断是否是中文*/
|
public static boolean isChineseChar(String str){
|
boolean temp = false;
|
Pattern p=Pattern.compile("[\u4e00-\u9fa5]");
|
Matcher m=p.matcher(str);
|
if(m.find()){
|
temp = true;
|
}
|
return temp;
|
}
|
|
/**去除字符串中不是中文的字符
|
*
|
*/
|
public static String deleteNoChinese(String str){
|
String name="";
|
if(checkNotNull(str)){
|
for(int i=0;i<str.length();i++){
|
String s = str.substring(i, i+1);
|
if(isChineseChar(s)){
|
name = name +s;
|
}
|
}
|
}
|
return name;
|
}
|
|
/**生成字母(全部是中文的)*/
|
public static String convertHanzi3Pinyin(String hanzi,boolean full){
|
hanzi = deleteNoChinese(hanzi);
|
hanzi = convertHanzi2Pinyin(hanzi,false);
|
return hanzi;
|
}
|
|
/***获取字符串拼音的第一个字母(大写)**/
|
public static String convertStringPinyinOne(String hanzi) {
|
if(SimpleTool.checkNotNull(hanzi)) {
|
//转化为便宜
|
hanzi = convertHanzi2Pinyin(hanzi,false);
|
//转化大写
|
hanzi = hanzi.toUpperCase();
|
/*//获取第一个
|
byte[] datas = hanzi.getBytes();
|
if(datas.length>0) {
|
byte[] datas2 = new byte[] {datas[0]};
|
hanzi = new String(datas2);
|
}else {
|
hanzi = "";
|
}*/
|
}
|
return hanzi;
|
}
|
|
|
/***将汉字转成拼音(取首字母或全拼)
|
* @param hanzi
|
* @param full 是否全拼
|
* @return
|
*/
|
public static String convertHanzi2Pinyin(String hanzi,boolean full){
|
//获取第一个字
|
/* if(checkNotNull(hanzi)){
|
boolean isHave = true;
|
Integer l = hanzi.length();
|
Integer index = 0;
|
while (isHave) {
|
String hanzi2 = hanzi.substring(index,index+1);
|
if(isChineseChar(hanzi2)){
|
isHave = false;
|
hanzi = hanzi2;
|
}else{
|
if(index<l-1){
|
index++;
|
}else{
|
isHave = false;
|
}
|
}
|
}
|
}
|
*/
|
//去除所有的空格
|
if(checkNotNull(hanzi)){
|
hanzi = hanzi.replaceAll(" ", "");
|
}
|
|
/***
|
* ^[\u2E80-\u9FFF]+$ 匹配所有东亚区的语言
|
* ^[\u4E00-\u9FFF]+$ 匹配简体和繁体
|
* ^[\u4E00-\u9FA5]+$ 匹配简体
|
*/
|
String regExp="^[\u4E00-\u9FFF]+$";
|
StringBuffer sb=new StringBuffer();
|
if(hanzi==null||"".equals(hanzi.trim())){
|
return "";
|
}
|
String pinyin="";
|
for(int i=0;i<hanzi.length();i++){
|
char unit=hanzi.charAt(i);
|
if(match(String.valueOf(unit),regExp)){//是汉字,则转拼音
|
pinyin=convertSingleHanzi2Pinyin(unit);
|
if(full){
|
sb.append(pinyin);
|
}else{
|
sb.append(pinyin.charAt(0));
|
}
|
}else{
|
sb.append(unit);
|
}
|
}
|
return sb.toString();
|
}
|
|
/***将单个汉字转成拼音
|
* @param hanzi
|
* @return
|
*/
|
private static String convertSingleHanzi2Pinyin(char hanzi){
|
HanyuPinyinOutputFormat outputFormat = new HanyuPinyinOutputFormat();
|
outputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
|
String[] res;
|
StringBuffer sb=new StringBuffer();
|
try {
|
res = PinyinHelper.toHanyuPinyinStringArray(hanzi,outputFormat);
|
sb.append(res[0]);//对于多音字,只用第一个拼音
|
} catch (Exception e) {
|
e.printStackTrace();
|
return "";
|
}
|
return sb.toString();
|
}
|
|
/***@param str 源字符串
|
* @param regex 正则表达式
|
* @return 是否匹配
|
*/
|
public static boolean match(String str,String regex){
|
Pattern pattern=Pattern.compile(regex);
|
Matcher matcher=pattern.matcher(str);
|
return matcher.find();
|
}
|
|
/** 读取 Excel文件内容(3.24 quan)
|
*
|
* @param excel_name File
|
* @return
|
* @throws Exception
|
*/
|
public static List<String[]> readExcelByeFile2(File excel_name) throws Exception {
|
// 结果集
|
List<String[]> list = new ArrayList<String[]>();
|
HSSFWorkbook hssfworkbook = new HSSFWorkbook(new FileInputStream(excel_name));
|
|
// 遍历该表格中所有的工作表,i表示工作表的数量 getNumberOfSheets表示工作表的总数
|
HSSFSheet hssfsheet = hssfworkbook.getSheetAt(0);
|
|
// 遍历该行所有的行,j表示行数 getPhysicalNumberOfRows行的总数
|
for (int j = 0; j < hssfsheet.getPhysicalNumberOfRows(); j++) {
|
HSSFRow hssfrow = hssfsheet.getRow(j);
|
if(hssfrow!=null){
|
int col = hssfrow.getPhysicalNumberOfCells();
|
// 单行数据
|
String[] arrayString = new String[col];
|
for (int i = 0; i < col; i++) {
|
HSSFCell cell = hssfrow.getCell(i);
|
if (cell == null) {
|
arrayString[i] = "";
|
} else if (cell.getCellType() == CellType.NUMERIC) {
|
// arrayString[i] = new Double(cell.getNumericCellValue()).toString();
|
short format = cell.getCellStyle().getDataFormat();
|
SimpleDateFormat sdf = null;
|
if(format == 14 || format == 31 || format == 57 || format == 58){
|
//日期
|
sdf = new SimpleDateFormat("yyyy-MM-dd");
|
}else if (format == 20 || format == 32) {
|
//时间
|
sdf = new SimpleDateFormat("HH:mm");
|
}else if (CellType.NUMERIC == cell.getCellType()) {
|
if (HSSFDateUtil.isCellDateFormatted(cell)) {
|
Date d = cell.getDateCellValue();
|
DateFormat formater = new SimpleDateFormat("yyyy年");
|
// DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
arrayString[i] = formater.format(d);
|
} else {
|
arrayString[i] = new BigDecimal(cell.getNumericCellValue()).toString();
|
}
|
}
|
} else {// 如果EXCEL表格中的数据类型为字符串型
|
arrayString[i] = cell.getStringCellValue().trim();
|
}
|
}
|
list.add(arrayString);
|
}
|
}
|
return list;
|
}
|
|
/**
|
* 读取 Excel文件内容
|
*
|
* @param excel_name
|
* @param header 是否包括表头
|
* @return
|
* @throws Exception
|
*/
|
public static List<String[]> readExcelByeFileData(File excel_name,boolean header) throws Exception {
|
// 结果集
|
List<String[]> list = new ArrayList<String[]>();
|
|
HSSFWorkbook hssfworkbook = new HSSFWorkbook(new FileInputStream(
|
excel_name));
|
|
// 遍历该表格中所有的工作表,i表示工作表的数量 getNumberOfSheets表示工作表的总数
|
for(int s=0;s<hssfworkbook.getNumberOfSheets();s++) {
|
HSSFSheet hssfsheet = hssfworkbook.getSheetAt(s);
|
int col = 0;
|
// 遍历该行所有的行,j表示行数 getPhysicalNumberOfRows行的总数 去除标题
|
for (int j = 0; j < hssfsheet.getPhysicalNumberOfRows(); j++) {
|
HSSFRow hssfrow = hssfsheet.getRow(j);
|
if(hssfrow!=null){
|
if(j == 0) {
|
col = hssfrow.getPhysicalNumberOfCells();
|
if(!header) {
|
//不包括表头
|
continue;
|
}
|
}
|
// 单行数据
|
String[] arrayString = new String[col];
|
for (int i = 0; i < col; i++) {
|
HSSFCell cell = hssfrow.getCell(i);
|
if (cell == null) {
|
arrayString[i] = "";
|
} else if (cell.getCellType() == CellType.NUMERIC) {
|
// arrayString[i] = new Double(cell.getNumericCellValue()).toString();
|
if (CellType.NUMERIC == cell.getCellType()) {
|
short format = cell.getCellStyle().getDataFormat();
|
if(format == 14 || format == 31 || format == 57 || format == 58){
|
//日期(中文时间格式的)
|
Date d = cell.getDateCellValue();
|
DateFormat formater = new SimpleDateFormat("yyyy年");
|
// DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
arrayString[i] = formater.format(d);
|
}else if (HSSFDateUtil.isCellDateFormatted(cell)) {
|
Date d = cell.getDateCellValue();
|
DateFormat formater = new SimpleDateFormat("yyyy年");
|
// DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
arrayString[i] = formater.format(d);
|
} else {
|
if(CellType.STRING == cell.getCellType()){
|
arrayString[i] =cell.getStringCellValue();
|
}else if(CellType.FORMULA==cell.getCellType()){
|
arrayString[i] =cell.getCellFormula();
|
}else if(CellType.NUMERIC== cell.getCellType()){
|
HSSFDataFormatter dataFormatter = new HSSFDataFormatter();
|
arrayString[i] =dataFormatter.formatCellValue(cell);
|
}
|
}
|
}
|
} else if(cell.getCellType() == CellType.BLANK){
|
arrayString[i] = "";
|
} else { // 如果EXCEL表格中的数据类型为字符串型
|
arrayString[i] = cell.getStringCellValue().trim();
|
}
|
}
|
list.add(arrayString);
|
}
|
}
|
}
|
return list;
|
}
|
|
/**
|
* 读取 Excel文件内容(学校信息专用)
|
*
|
* @param excel_name
|
* @return
|
* @throws Exception
|
*/
|
public static List<String[]> readExcelByeFile(File excel_name) throws Exception {
|
// 结果集
|
List<String[]> list = new ArrayList<String[]>();
|
|
HSSFWorkbook hssfworkbook = new HSSFWorkbook(new FileInputStream(
|
excel_name));
|
|
// 遍历该表格中所有的工作表,i表示工作表的数量 getNumberOfSheets表示工作表的总数
|
for(int s=0;s<hssfworkbook.getNumberOfSheets();s++) {
|
HSSFSheet hssfsheet = hssfworkbook.getSheetAt(s);
|
int col = 0;
|
// 遍历该行所有的行,j表示行数 getPhysicalNumberOfRows行的总数 去除标题
|
for (int j = 0; j < hssfsheet.getPhysicalNumberOfRows(); j++) {
|
HSSFRow hssfrow = hssfsheet.getRow(j);
|
if(hssfrow!=null){
|
if(j == 0) {
|
col = hssfrow.getPhysicalNumberOfCells();
|
}else {
|
// int col = hssfrow.getPhysicalNumberOfCells();
|
// 单行数据
|
String[] arrayString = new String[col];
|
for (int i = 0; i < col; i++) {
|
HSSFCell cell = hssfrow.getCell(i);
|
if (cell == null) {
|
arrayString[i] = "";
|
} else if (cell.getCellType() == CellType.NUMERIC) {
|
// arrayString[i] = new Double(cell.getNumericCellValue()).toString();
|
if (CellType.NUMERIC == cell.getCellType()) {
|
short format = cell.getCellStyle().getDataFormat();
|
if(format == 14 || format == 31 || format == 57 || format == 58){
|
//日期(中文时间格式的)
|
Date d = cell.getDateCellValue();
|
DateFormat formater = new SimpleDateFormat("yyyy年");
|
// DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
arrayString[i] = formater.format(d);
|
}else if (HSSFDateUtil.isCellDateFormatted(cell)) {
|
Date d = cell.getDateCellValue();
|
DateFormat formater = new SimpleDateFormat("yyyy年");
|
// DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
arrayString[i] = formater.format(d);
|
} else {
|
if(CellType.STRING == cell.getCellType()){
|
arrayString[i] =cell.getStringCellValue();
|
}else if(CellType.FORMULA==cell.getCellType()){
|
arrayString[i] =cell.getCellFormula();
|
}else if(CellType.NUMERIC== cell.getCellType()){
|
HSSFDataFormatter dataFormatter = new HSSFDataFormatter();
|
arrayString[i] =dataFormatter.formatCellValue(cell);
|
}
|
}
|
}
|
} else if(cell.getCellType() == CellType.BLANK){
|
arrayString[i] = "";
|
} else { // 如果EXCEL表格中的数据类型为字符串型
|
cell.setCellType(CellType.STRING);
|
String name = cell.getStringCellValue().trim();
|
if(name.equals("-")) {
|
arrayString[i] = "";
|
}else {
|
arrayString[i] = name;
|
}
|
}
|
}
|
list.add(arrayString);
|
}
|
}
|
}
|
}
|
return list;
|
}
|
|
/**获取字符串里面的数字,按顺序排序*/
|
public static String stringNumber(String data) {
|
String da = null;
|
String regEc = "[^0-9]";
|
Pattern pattern = Pattern.compile(regEc);
|
Matcher m = pattern.matcher(data);
|
da = m.replaceAll("").trim();
|
return da;
|
}
|
|
/**
|
* @param url:请求url
|
* @param content: 请求体(参数)
|
* @return errorStr:错误信息;status:状态码,response:返回数据
|
* @throws JSONException
|
*/
|
public static JSONObject requestData(String url, String content) throws JSONException {
|
JSONObject obj = new JSONObject();
|
String errMsg_r = "";
|
String status_r = "0";
|
String response = "";
|
//PrintWriter out = null;
|
DataOutputStream out = null;
|
BufferedReader in = null;
|
try {
|
URL realUrl = new URL(url);
|
// 打开和URL之间的连接
|
URLConnection conn = realUrl.openConnection();
|
HttpURLConnection httpUrlConnection = (HttpURLConnection) conn;
|
// 设置请求属性
|
httpUrlConnection.setRequestProperty("Content-type", "application/json;charset=UTF-8");
|
//httpUrlConnection.setRequestProperty("Content-Type", "application/json");
|
//httpUrlConnection.setRequestProperty("Charset", "UTF-8");
|
httpUrlConnection.setRequestProperty("x-adviewrtb-version", "2.1");
|
// 发送POST请求必须设置如下两行
|
httpUrlConnection.setDoOutput(true);
|
httpUrlConnection.setDoInput(true);
|
// 获取URLConnection对象对应的输出流
|
out = new DataOutputStream(httpUrlConnection.getOutputStream());
|
//out = new PrintWriter(httpUrlConnection.getOutputStream());
|
// 发送请求参数
|
//out.write(content);
|
out.write(content.getBytes("UTF-8"));
|
// flush输出流的缓冲
|
out.flush();
|
httpUrlConnection.connect();
|
// 定义BufferedReader输入流来读取URL的响应
|
// in = new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream()));
|
String wxMsgXml = IOUtils.toString(httpUrlConnection.getInputStream(), "utf-8");
|
System.out.println("wxMsgXml:"+wxMsgXml);
|
if(SimpleTool.checkNotNull(wxMsgXml)) {
|
obj = JSONObject.fromObject(wxMsgXml);
|
}
|
/* String line;
|
while ((line = in.readLine()) != null) {
|
response += line;
|
} */
|
status_r = new Integer(httpUrlConnection.getResponseCode()).toString();
|
} catch (Exception e) {
|
System.out.println("发送 POST 请求出现异常!" + e);
|
errMsg_r = e.getMessage();
|
e.printStackTrace();
|
}
|
// 使用finally块来关闭输出流、输入流
|
finally {
|
try {
|
if (out != null) { out.close();}
|
if (in != null) {in.close();}
|
} catch (Exception ex) {
|
ex.printStackTrace();
|
}
|
}
|
obj.put("errMsg_r", errMsg_r);
|
obj.put("status_r", status_r);
|
return obj;
|
}
|
|
/**随机生成字数(整数)(包括 0)
|
* @param maxNumber 最大值
|
* @return
|
*/
|
public static Integer randomData(Integer maxNumber) {
|
java.util.Random r=new java.util.Random();
|
return r.nextInt(maxNumber);
|
}
|
|
private static final String[] HEADERS_TO_TRY = {"X-Forwarded-For", "Proxy-Client-IP", "WL-Proxy-Client-IP",
|
"HTTP_X_FORWARDED_FOR", "HTTP_X_FORWARDED", "HTTP_X_CLUSTER_CLIENT_IP", "HTTP_CLIENT_IP",
|
"HTTP_FORWARDED_FOR", "HTTP_FORWARDED", "HTTP_VIA", "REMOTE_ADDR", "X-Real-IP"};
|
|
/**
|
* getClientIpAddress:(获取用户ip,可穿透代理). <br/>
|
* @param request
|
* @return
|
* @author chenjiahe
|
* @Date 2018年3月2日下午4:41:47
|
* @since JDK 1.7
|
*/
|
public static String getClientIpAddress(HttpServletRequest request) {
|
for (String header : HEADERS_TO_TRY) {
|
String ip = request.getHeader(header);
|
if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
|
return ip;
|
}
|
}
|
return request.getRemoteAddr();
|
}
|
|
}
|