JavaWeb中POI导入和导出Excel、Map键值类型转换、时间格式化、对象赋值等常见工具类集锦

导入表格解析工具类

使用前先在maven项目中添加依赖

			org.apache.poi
			poi-ooxml
			3.15
		
ImportExcelUtil.java
package com.kilomob.powernetwork.permission.common;

import java.io.InputStream;
import java.io.PushbackInputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.kilomob.powernetwork.common.util.MapUtil;

public class ImportExcelUtil {

	
	/**
	 * 
	 * @Description map配置,名称为value,key为字段名
	 * @param in
	 * @param fileName
	 * @param map
	 * @return
	 * @throws Exception
	 * List>
	 * @exception:
	 * @author: fengjk
	 * @time:2017年5月3日 下午8:27:10
	 */
	public static List> getListByExcel(InputStream in, String fileName, Map map)
			throws Exception {
		// 创建Excel工作薄
		Workbook work = getWorkbook(in, fileName);
		if (null == work) {
			throw new Exception("创建Excel工作薄为空!");
		}
		Sheet sheet = null;
		Row row = null;
		Cell cell = null;

		List> dataListMaps = new ArrayList>();
		// 遍历Excel中所有的sheet
		for (int i = 0; i < work.getNumberOfSheets(); i++) {
			sheet = work.getSheetAt(i);
			if (sheet == null) {
				continue;
			}
			List titleList = new ArrayList();
			int colNum = 0; // 列数
			Row row0 = sheet.getRow(0);
			if(row0 == null){
				throw new RuntimeException("导入模版不正确,请下载正确的模版导入");
			}
			List modelKeyList = new ArrayList(20);
			modelKeyList.addAll(map.keySet());

			colNum = row0.getPhysicalNumberOfCells();
			for (int i1 = 0; i1 < colNum; i1++) {
				String nameString = (String) getCellValue(row0.getCell((short) i1));
				if(StringUtils.isNotBlank(nameString) && !nameString.equals(MapUtil.getStringValue(map,modelKeyList.get(i1)))){
					throw new RuntimeException("导入模版不正确,请下载正确的模版导入");
				}
				nameString = nameString.replace(" ", "");
				titleList.add(nameString);// 得到列名
			}

			// 遍历当前sheet中的所有行
			for (int j = sheet.getFirstRowNum(); j <=sheet.getLastRowNum(); j++) {
				row = sheet.getRow(j);
				if (row == null ||row.getFirstCellNum() == j) {
					continue;
				}
				// 遍历所有的列
				Map mapCell = new HashMap();
				for (int y = row.getFirstCellNum(); y <= row.getPhysicalNumberOfCells(); y++) {
					cell = row.getCell(y);
					if (null != cell) {
						mapCell.put(titleList.get(y), getCellValue(cell));
					}
				}
				Map mapNew = new HashMap<>();
				for (String key : map.keySet()) {
					mapNew.put(key, mapCell.get(map.get(key)));
				}
				dataListMaps.add(mapNew);
			}
		}
		work.close();
		return dataListMaps;
	}

	
	/**
	 * 描述:根据文件后缀,自适应上传文件的版本
	 * 
	 * @param inStr
	 *            ,fileName
	 * @return
	 * @throws Exception
	 */
	public static Workbook getWorkbook(InputStream inStr, String fileName)
			throws Exception {
		String fileType = fileName.substring(fileName.lastIndexOf("."));
		if(! inStr.markSupported()) {  
			inStr = new PushbackInputStream(inStr, 8);  
        }  
		if(POIFSFileSystem.hasPOIFSHeader(inStr)) {  
            return new HSSFWorkbook(inStr);  
        }  
        if(POIXMLDocument.hasOOXMLHeader(inStr)) {  
            return new XSSFWorkbook(OPCPackage.open(inStr));  
        }  
		throw new Exception("解析的文件格式有误!");
		
	}

	/**
	 * 描述:对表格中数值进行格式化
	 * 
	 * @param cell
	 * @return
	 */
	public static Object getCellValue(Cell cell) {
		Object value = null;
		DecimalFormat df = new DecimalFormat("0"); // 格式化number String字符
		SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd"); // 日期格式化
		DecimalFormat df2 = new DecimalFormat("0.00"); // 格式化数字

		switch (cell.getCellType()) {
		case Cell.CELL_TYPE_STRING:
			value = cell.getRichStringCellValue().getString();
			break;
		case Cell.CELL_TYPE_NUMERIC:
			if ("General".equals(cell.getCellStyle().getDataFormatString())) {
				value = df.format(cell.getNumericCellValue());
			} else if ("m/d/yy".equals(cell.getCellStyle()
					.getDataFormatString())) {
				value = sdf.format(cell.getDateCellValue());
			} else {
				value = df2.format(cell.getNumericCellValue());
			}
			break;
		case Cell.CELL_TYPE_BOOLEAN:
			value = cell.getBooleanCellValue();
			break;
		case Cell.CELL_TYPE_BLANK:
			value = "";
			break;
		default:
			break;
		}
		return value;
	}




}
使用例子
	File file = new File(path); // path文件路径
	InputStream in = new FileInputStream(file);
	List> dataList = ImportExcelUtil.getListByExcel(in, file.getName(), this.getExcelColumMap());
	
	/**
	 * 
	 * @Description Map中value对应Excel列名,key对应上面解析出来Map数据的key
	 * @return
	 * Map
	 * @exception:
	 * @author: fengjk
	 * @time:2017年4月14日 下午2:14:02
	 */
	public Map getExcelColumMap(){
		Map columMap = new LinkedHashMap();
		columMap.put("name", "地区");
		columMap.put("longilatitude", "经纬度");
		
		return columMap;
	}

导出表格工具类

ExportExcelUtil.java
package com.kilomob.powernetwork.managerweb.util;



import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
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 org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.kilomob.powernetwork.common.excel.entity.ColDefine;
import com.kilomob.powernetwork.common.excel.entity.ExcelColmnTplConfig;
import com.kilomob.powernetwork.common.excel.entity.ExcelTplConfig;
import com.kilomob.powernetwork.common.util.MapUtil;
import com.kilomob.powernetwork.common.util.TimeFormatHelper;
/**
 * @Description:TODO
 * @author: fengjk
 * @time:2017年4月10日 上午10:36:09
 */
public class ExportExcelUtil {

	private static final Logger logger = LoggerFactory.getLogger(ExportExcelUtil.class);

	
	protected String errorDbCol;
	
	public String getErrorDbCol() {
		return "O_MESG";
	}
	
	
	public String exportData(ExcelTplConfig tplCfg, List> dataList,String sheetName,String tempfilePath) {
		
		FileOutputStream out;
		String exportXlsName= "/export-"+TimeFormatHelper.getFormatDate(new Date(), TimeFormatHelper.TIME_FORMAT_G)+".xls";

		try {
			File folder = new File(tempfilePath);
			if(!folder.exists()) {
				folder.mkdir();
			}
			String filePath = tempfilePath + exportXlsName;

			HSSFWorkbook wb = new HSSFWorkbook();
			HSSFSheet sheet = wb.createSheet(sheetName);
			
			List columnList = new ArrayList(tplCfg.getColumnList());
			
			HSSFRow row = sheet.createRow(0);
			for(int i=0; i data = dataList.get(i);
				for(int j=0; j
表格存储类(列名和映射实体对象对应的字段名)
ExcelColmnTplConfig.java
package com.kilomob.powernetwork.common.excel.entity;

import java.io.Serializable;

public class ExcelColmnTplConfig implements Serializable{
	private static final long serialVersionUID = 1L;
	private String fileCol; // 对应导出数据Map中的key
	private String dbCol; // 对应导出数据Map中的列名
	private Boolean isNotNull = false;
	public String getFileCol() {
		return fileCol;
	}
	public void setFileCol(String fileCol) {
		this.fileCol = fileCol;
	}
	public String getDbCol() {
		return dbCol;
	}
	public void setDbCol(String dbCol) {
		this.dbCol = dbCol;
	}
	public Boolean getIsNotNull() {
		return isNotNull;
	}
	public void setIsNotNull(Boolean isNotNull) {
		this.isNotNull = isNotNull;
	}
}
自定义表格模板类ExcelTplConfig.java
package com.kilomob.powernetwork.common.excel.entity;

import java.io.Serializable;
import java.util.List;

public class ExcelTplConfig implements Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String templateId;
	private int sheetNum = 0;
	
	private int titleRowNum = 0;
	
	private int dataRowNum = 1; 
	
	/**
	 * 模板路径
	 */
	private String templatePath;
	
	public String getTemplatePath() {
		return templatePath;
	}

	public void setTemplatePath(String templatePath) {
		this.templatePath = templatePath;
	}

	/**
	 * 自定义文件与数据库表列之间的映射关系
	 */
	private String columnDefineHandler;
	
	/**
	 * 数据入库处理逻辑,默认走ExcelDataHandlerBO
	 */
	private String fileInputHandler;
	
	public String getFileInputHandler() {
		return fileInputHandler;
	}

	public void setFileInputHandler(String fileInputHandler) {
		this.fileInputHandler = fileInputHandler;
	}

	/**
	 * 数据清洗校验逻辑
	 */
	private String dataCleanHandler;
	
	/**
	 * 数据入库逻辑
	 */
	private String dataDoneHandler;
	
	private String eltBoName;
	
	public String getEltBoName() {
		return eltBoName;
	}

	public void setEltBoName(String eltBoName) {
		this.eltBoName = eltBoName;
	}

	public String getTemplateId() {
		return templateId;
	}

	public void setTemplateId(String templateId) {
		this.templateId = templateId;
	}

	public int getSheetNum() {
		return sheetNum;
	}

	public void setSheetNum(int sheetNum) {
		this.sheetNum = sheetNum;
	}

	public int getTitleRowNum() {
		return titleRowNum;
	}

	public void setTitleRowNum(int titleRowNum) {
		this.titleRowNum = titleRowNum;
	}

	public int getDataRowNum() {
		return dataRowNum;
	}

	public void setDataRowNum(int dataRowNum) {
		this.dataRowNum = dataRowNum;
	}

	public String getColumnDefineHandler() {
		return columnDefineHandler;
	}

	public void setColumnDefineHandler(String columnDefineHandler) {
		this.columnDefineHandler = columnDefineHandler;
	}

	public String getDataCleanHandler() {
		return dataCleanHandler;
	}

	public void setDataCleanHandler(String dataCleanHandler) {
		this.dataCleanHandler = dataCleanHandler;
	}

	public String getDataDoneHandler() {
		return dataDoneHandler;
	}

	public void setDataDoneHandler(String dataDoneHandler) {
		this.dataDoneHandler = dataDoneHandler;
	}

	public String getTableName() {
		return tableName;
	}

	public void setTableName(String tableName) {
		this.tableName = tableName;
	}

	public List getColumnList() {
		return columnList;
	}

	public void setColumnList(List columnList) {
		this.columnList = columnList;
	}

	private String tableName;
	
	private List columnList;
	
	/**
	 * 导入模板定义名
	 */
	private String title;

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}
	
}
自定义表格样式工具类PoiExcelUtils.java
package com.kilomob.powernetwork.managerweb.util;

import java.text.SimpleDateFormat;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.DVConstraint;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataValidation;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.util.CellRangeAddressList;

public class PoiExcelUtils {
	public static String SHEET_NAME_SPLIT_CHAR="-";
	public static int MAX_NUM_PRE_PAGE = 60000; // 一个表格的最大写入数量

	public static int START_ROW = 0;

	public static int START_CELL = 0;

	public static HSSFCellStyle getHeadNormalStyle(HSSFWorkbook workbook) {
		HSSFFont headfont = workbook.createFont();
		headfont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		headfont.setColor(HSSFColor.BLACK.index);
		HSSFCellStyle headStyle = workbook.createCellStyle();
		headStyle.setFillForegroundColor(HSSFColor.LIGHT_GREEN.index);
		headStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		headStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		headStyle.setFont(headfont);
		headStyle.setWrapText(true);
		headStyle.setBorderBottom((short) 1);
		headStyle.setBorderLeft((short) 1);
		headStyle.setBorderTop((short) 1);
		headStyle.setBorderRight((short) 1);
		return headStyle;
	}

	public static HSSFCellStyle getHeadNotNullStyle(HSSFWorkbook workbook) {
		HSSFFont notNullfont = workbook.createFont();
		notNullfont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		notNullfont.setColor(HSSFColor.RED.index);
		HSSFCellStyle notNullStyle = workbook.createCellStyle();
		notNullStyle.setFillForegroundColor(HSSFColor.LIGHT_GREEN.index);
		notNullStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		notNullStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		notNullStyle.setFont(notNullfont);
		notNullStyle.setBorderBottom((short) 1);
		notNullStyle.setBorderLeft((short) 1);
		notNullStyle.setBorderTop((short) 1);
		notNullStyle.setBorderRight((short) 1);
		return notNullStyle;
	}

	public static HSSFCellStyle getBodyStyle(HSSFWorkbook workbook) {
		HSSFCellStyle bodyStyle = workbook.createCellStyle();
		bodyStyle.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
		bodyStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		bodyStyle.setAlignment(HSSFCellStyle.ALIGN_LEFT);
		bodyStyle.setBorderBottom((short) 1);
		bodyStyle.setBorderLeft((short) 1);
		bodyStyle.setBorderTop((short) 1);
		bodyStyle.setBorderRight((short) 1);
		return bodyStyle;
	}
	
    
    public static HSSFCellStyle getBodyNotNullStyle(HSSFWorkbook workbook) {
		HSSFFont notNullfont = workbook.createFont();
		notNullfont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		notNullfont.setColor(HSSFColor.RED.index);
		HSSFCellStyle bodyStyle = workbook.createCellStyle();
		bodyStyle.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
		bodyStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		bodyStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		bodyStyle.setFont(notNullfont);
		bodyStyle.setBorderBottom((short) 1);
		bodyStyle.setBorderLeft((short) 1);
		bodyStyle.setBorderTop((short) 1);
		bodyStyle.setBorderRight((short) 1);
		return bodyStyle;
	}
	
	public static HSSFCellStyle getBodyWhiteStyle(HSSFWorkbook workbook) {
		HSSFCellStyle bodyStyle = workbook.createCellStyle();
		bodyStyle.setFillForegroundColor(HSSFColor.WHITE.index);
		bodyStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		bodyStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		bodyStyle.setBorderBottom((short) 1);
		bodyStyle.setBorderLeft((short) 1);
		bodyStyle.setBorderTop((short) 1);
		bodyStyle.setBorderRight((short) 1);
		return bodyStyle;
	}

	
	/** 
	    * 方法名称:SetDataValidation 
	    * 内容摘要:设置数据有效性 
	    * @param firstRow 
	    * @param firstCol 
	    * @param endRow 
	    * @param endCol  
	    */  
	 public static HSSFDataValidation setDataValidation(String[] textList,int firstRow,  
			 int firstCol, int endRow, int endCol) {  
	    //加载下拉列表内容  
	    DVConstraint constraint = DVConstraint.createExplicitListConstraint(textList);        
	    CellRangeAddressList regions = new CellRangeAddressList(firstRow,endRow, firstCol, endCol);
	    //数据有效性对象  
	    HSSFDataValidation data_validation = new HSSFDataValidation(regions, constraint);
	    return data_validation;  
	}
	 
	 public static Object getCellValue(Cell c){
			Object value=null;
			CellStyle s = c.getCellStyle();
			short i = s.getDataFormat();
			switch (c.getCellType())
		      {
		      case 3:
		        break;
		      case 4:
		        if (c.getBooleanCellValue())
		        	value = ("true");
		        else
		          value = ("false");
		        break;
		      case 0:
		        if(DateUtil.isCellDateFormatted(c)){
		        	value=c.getDateCellValue();
		        	SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		        	value = dateformat.format(value);
		        }else{
		        	value = c.getNumericCellValue();
		        }
		        break;
		      case 1:
		        value = StringUtils.trimToEmpty(c.getRichStringCellValue().getString());
		        break;
		      case 2:
		      default:
		      }
			return value;
		}



}
使用例子
		Map columMap = this.getExcelColumnMap();

		List columnList = new ArrayList();
		ExcelTplConfig tplCfg = new ExcelTplConfig();
		for (String key : columMap.keySet()) {
			ExcelColmnTplConfig eltColmnTplConfig = new ExcelColmnTplConfig();
			eltColmnTplConfig.setDbCol(key);
			eltColmnTplConfig.setFileCol(columMap.get(key));
			columnList.add(eltColmnTplConfig);
			tplCfg.setColumnList(columnList);
		}

		List> dataList = null; // 此处的null替换成导出的数据即可
		
		
		// 对应表中的列名和映射的字段名
		private Map getExcelColumnMap() {
		Map columMap = new LinkedHashMap();
		columMap.put("billId", "账单ID");
		columMap.put("billCycle", "计费周期");
		columMap.put("accountId", "账户ID");
		columMap.put("accountName", "账户名");
		columMap.put("operator", "运营商");
		columMap.put("devices", "设备数量");
		columMap.put("allCost", "总费用");
		columMap.put("flow", "已用流量(MB)");
		columMap.put("isBill", "是否计费");
		columMap.put("billDate", "账单日期");
		return columMap;
		}
		
		// 这里应当抽取出来放在控制层(与web层同个模块),笔者存储文件路径是放在web模块中,不然会出现路径错误
		String filePath = request.getServletContext().getContextPath();
		String realPath = request.getServletContext().getRealPath("/");
		String sheetName = "账单";
		String exportXlsName = ExportExcelUtil.exportData(tplCfg, dataList,
					sheetName, realPath);
前台通过请求filePath+realPath路径即可下载导出文件。

Map中value类型转换工具类

MapUtils.java
package com.kilomob.powernetwork.common.util;

import java.math.BigDecimal;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONObject;

public class MapUtil {
	
	public static String getStringValue(Map map, String key) {
		if(map == null) return null;
		
		Object value = map.get(key);
		if (value == null) {
			return null;
		}
		if (value instanceof String) {
			return StringUtils.trimToEmpty((String) value);
		/*} else if (value instanceof CLOB) {
			return oracleClob2Str((CLOB) value);*/
		} else if (value instanceof JSONObject) {
			return ((JSONObject)value).getString("value");
		} else {
			return value.toString();
		}
	}
	
	public static int getIntValue(Map map, String key) {
		if(map == null) return 0;
		
		Object value = map.get(key);
		if (value == null) {
			return 0;
		}
		if (value instanceof BigDecimal) {
			return ((BigDecimal) value).intValue();
		}else if(value instanceof Long){
			return ((Long)value).intValue();
		}else if(value instanceof Short){
			return ((Short)value).intValue(); 
		}else if(value instanceof Integer){
			return ((Integer)value).intValue();
		}else if(value instanceof Double){
			return ((Double)value).intValue();
		}else if(value instanceof String){
			if(StringUtils.isBlank(value+"")) {
				return 0;
			}else {
				try {
					return Integer.parseInt(value+"");
				}catch(Exception e) {
					throw new RuntimeException("无法将key【"+key+"】,value【"+value+"】转换为Integer类型!");
				}
			}
		} else {
			throw new RuntimeException("无法将key【"+key+"】,value【"+value+"】转换为Integer类型!");
		}
	}
	public static Long getLongValue(Map map, String key) {
		if(map == null) return 0l;
		
		Object value = map.get(key);
		if (value == null) {
			return 0l;
		}
		if (value instanceof BigDecimal) {
			return ((BigDecimal) value).longValue();
		}else if(value instanceof Long){
			return (Long)value;
		}else if(value instanceof Short){
			return ((Short)value).longValue(); 
		}else if(value instanceof Integer){
			return ((Integer)value).longValue();
		}else if(value instanceof String){
			if(StringUtils.isBlank(value+"")) {
				return 0l;
			}else {
				try {
					return Long.parseLong(value+"");
				}catch(Exception e) {
					throw new RuntimeException("无法将key【"+key+"】,value【"+value+"】转换为Long类型!");
				}
			}
		} else {
			throw new RuntimeException("无法将key【"+key+"】,value【"+value+"】转换为Long类型!");
		}
	}

}

时间格式化工具类

TimeFormatHelper.java
package com.kilomob.powernetwork.common.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TimeFormatHelper {
	static Logger logHome = LoggerFactory.getLogger(TimeFormatHelper.class);
	public static final String TIME_FORMAT_A = "yyyy-MM-dd HH:mm:ss";
	public static final String TIME_FORMAT_B = "yyyyMMddHHmmss";
	public static final String TIME_FORMAT_C = "yyyy-MM-dd HH:mm:ss:SSS";
	public static final String TIME_FORMAT_D = "yyyy-MM-dd HH:mm:ss.SSS";
	public static final String TIME_FORMAT_E = "yyyyMMddHHmmssSSS";
	public static final String TIME_FORMAT_F = "yyyy-MM-dd'T'HH:mm:ss.SSS";
	public static final String TIME_FORMAT_G = "yyyyMMddHHmmssSSS";
	public static final String DATE_FORMAT = "yyyy-MM-dd";
	public static final String TELCORDIA_DATE_FORMAT = "MM-dd-yyyy";
	public static final String YEAR_FORMAT = "yyyy";
	public static final String MONTH_FORMAT = "yyyy-MM";
	public static final String MONTH_FORMAT_A = "yyyyMM";
	public static final String TIME_FORMAT_SYSTEM = "EEE MMM dd HH:mm:ss zzz yyyy";
	public static final String DATE_FORMAT_B = "yyMMdd";
	public static final String DATE_FORMAT_APM = "yyyy/MM/dd HH:mm a Z";
	public static final String DATE_FORMAT_A = "yyyy/MM/dd";

	private TimeFormatHelper() {
	}

	public static String getFormatDate(Date date, String format) {
		String dateStr = null;
		try {
			if (date != null) {
				SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
				dateStr = simpleDateFormat.format(date);
			}
		} catch (Exception ex) {
			logHome.error("", ex);
		}
		return dateStr;
	}

	public static Date convertDate(String dateStr, String format) {
		java.util.Date date = new Date();
		try {
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
			date = simpleDateFormat.parse(dateStr);
		} catch (Exception ex) {
			logHome.error("", ex);
		}
		return date;
	}

	public static Date convertDate(String dateStr, String format, Locale locale) {
		java.util.Date date = new Date();
		try {
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format,
					locale);
			date = simpleDateFormat.parse(dateStr);
		} catch (Exception ex) {
			logHome.error("", ex);
		}
		return date;
	}

	public static Date convertDate(String dateStr) {
		if (StringUtils.trimToNull(dateStr) == null) {
			return null;
		}
		java.util.Date date = null;
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
				TimeFormatHelper.TIME_FORMAT_A);
		try {
			date = simpleDateFormat.parse(dateStr);
		} catch (ParseException ex) {
			simpleDateFormat = new SimpleDateFormat(DATE_FORMAT);
			try {
				date = simpleDateFormat.parse(dateStr);
			} catch (ParseException e) {
				try {
					date = new Date(Long.valueOf(dateStr));
				} catch (Exception ec) {
					try {
						date = simpleDateFormat.parse("1999-01-01");
					} catch (ParseException e1) {
						logHome.error("无法翻译" + dateStr + "取初始化时间!");
					}
				}
			}
		}
		return date;
	}

	public static Date checkIsDate(String dateStr) {
		java.util.Date date = null;
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
				TimeFormatHelper.TIME_FORMAT_A);
		try {
			date = simpleDateFormat.parse(dateStr);
		} catch (ParseException ex) {
			simpleDateFormat = new SimpleDateFormat(
					TimeFormatHelper.DATE_FORMAT);
			try {
				date = simpleDateFormat.parse(dateStr);
			} catch (ParseException e) {
				try {
					date = new Date(Long.valueOf(dateStr));
				} catch (Exception ec) {
					logHome.error("无法翻译" + dateStr + "取初始化时间!");
				}
			}
		}
		return date;
	}

	public static java.sql.Timestamp getFormatTimestamp(String dateStr) {
		String format = getTimeFormat(dateStr);
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
		java.util.Date date = null;
		try {
			date = simpleDateFormat.parse(dateStr);
		} catch (Exception ex) {
			logHome.error("日期格式转换错误", ex);
		}
		java.sql.Timestamp timestamp = getFormatTimestamp(date, format);
		return timestamp;
	}

	public static String getTimeFormat(String dateStr) {
		String timeFormat = TIME_FORMAT_A;
		if (dateStr != null) {
			String[] str1 = dateStr.split(":");
			String[] str2 = dateStr.split("-");
			boolean existDot = dateStr.contains(".");
			if (str1.length == 3 && str2.length == 3) {
				if (!existDot) {
					timeFormat = TIME_FORMAT_A;
				} else {
					timeFormat = TIME_FORMAT_D;
				}
			} else if (str1.length == 1 && str2.length == 3) {
				timeFormat = DATE_FORMAT;
			} else if (dateStr.length() == 14) {
				timeFormat = TIME_FORMAT_B;
			} else if (dateStr.length() == 6) {
				timeFormat = DATE_FORMAT_B;
			} else if (dateStr.length() == 4) {
				timeFormat = YEAR_FORMAT;
			} else if (str1.length == 4) {
				timeFormat = TIME_FORMAT_C;
			}
		}
		System.out.println("timeFormat is:" + timeFormat);
		return timeFormat;
	}

	public static java.sql.Timestamp getFormatTimestamp(java.util.Date date,
			String format) {
		java.sql.Timestamp timestamp = null;
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
		String resStr = simpleDateFormat.format(date);
		timestamp = java.sql.Timestamp.valueOf(resStr);
		return timestamp;
	}
	
	
	public static Date getNowDate(Date date,String format) {
	    SimpleDateFormat formatter = new SimpleDateFormat(format);
	    String dateString = formatter.format(date);
		try {
			Date converDate = formatter.parse(dateString);
			return converDate;
		} catch (ParseException e) {
			logHome.error("无法翻译时间!");
		}
	   return null;
	}

	public String getTimeString(Date date){
		return this.getFormatDate(date, TIME_FORMAT_E);
	}
	
	/**
	 * @Description:取系统默认最大时间
	 * @return
	 * Date
	 * @exception:
	 * @author: fengjk
	 * @time:2017年4月10日 下午5:25:20
	 */
	public static Date getSysMaxDate() {
		java.util.Date date = null;
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
				TimeFormatHelper.DATE_FORMAT);
		try {
			date = simpleDateFormat.parse("2030-12-30");
		} catch (ParseException e1) {
			logHome.error("无法翻译时间!");
		}

		return date;
	}

}

对象赋值工具类

BeanUtils.java
package com.kilomob.powernetwork.common.util;

import java.lang.reflect.Field;

/**
 * 
 * @Description 不同对象赋值
 * @author fengjk
 * @date 2017-4-12 下午4:19:35
 */
public class BeanUtil {
	/**
	 * 
	 * @Description source资源赋值对象,target被赋值对象
	 * @author fengjk
	 * @date 2017-6-14 下午6:33:06
	 */
	public static void beanCopy(Object source, Object target) throws Exception {
		if (source == null || target == null) {
			throw new Exception("param is null.");
		}
		Field sourceField[] = source.getClass().getDeclaredFields();
		Field targetField[] = target.getClass().getDeclaredFields();
		if (sourceField == null || sourceField.length == 0) {
			throw new Exception("Source bean no properties.");
		}
		if (targetField == null || targetField.length == 0) {
			throw new Exception("Target bean no properties.");
		}
		for (Field tf : targetField) {
			tf.setAccessible(true);
			for (Field sf : sourceField) {
				sf.setAccessible(true);
				String tfType = tf.getType().getName();
				String sfType = sf.getType().getName();
				if (tf.getName().equals(sf.getName()) && tfType.equals(sfType)) {
					tf.set(target, sf.get(source));
					break;
				}
			}
		}
	}
}

总结

文中例子都是笔者抽取出来的,相信在理解的基础上都能上手。如有笔误,麻烦告知一声,万分感谢!欢迎加群探讨学习,qq:583138104









你可能感兴趣的:(Java,Web)