導入表格解析工具類
使用前先在maven項目中添加依賴
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15</version>
</dependency>
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<Map<String,Object>>
* @exception:
* @author: fengjk
* @time:2017年5月3日 下午8:27:10
*/
public static List<Map<String, Object>> getListByExcel(InputStream in, String fileName, Map<String, String> 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<Map<String, Object>> dataListMaps = new ArrayList<Map<String, Object>>();
// 遍歷Excel中所有的sheet
for (int i = 0; i < work.getNumberOfSheets(); i++) {
sheet = work.getSheetAt(i);
if (sheet == null) {
continue;
}
List<String> titleList = new ArrayList<String>();
int colNum = 0; // 列數
Row row0 = sheet.getRow(0);
if(row0 == null){
throw new RuntimeException("導入模版不正確,請下載正確的模版導入");
}
List<String> modelKeyList = new ArrayList<String>(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<String, Object> mapCell = new HashMap<String, Object>();
for (int y = row.getFirstCellNum(); y <= row.getPhysicalNumberOfCells(); y++) {
cell = row.getCell(y);
if (null != cell) {
mapCell.put(titleList.get(y), getCellValue(cell));
}
}
Map<String, Object> 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<Map<String, Object>> dataList = ImportExcelUtil.getListByExcel(in, file.getName(), this.getExcelColumMap());
/**
*
* @Description Map中value對應Excel列名,key對應上面解析出來Map數據的key
* @return
* Map<String,String>
* @exception:
* @author: fengjk
* @time:2017年4月14日 下午2:14:02
*/
public Map<String,String> getExcelColumMap(){
Map<String,String> columMap = new LinkedHashMap<String,String>();
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<Map<String, Object>> 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<ExcelColmnTplConfig> columnList = new ArrayList<ExcelColmnTplConfig>(tplCfg.getColumnList());
HSSFRow row = sheet.createRow(0);
for(int i=0; i<columnList.size(); i++){
ExcelColmnTplConfig column = columnList.get(i);
HSSFCell cell = row.createCell(i);
HSSFCellStyle headCellStyle = PoiExcelUtils.getHeadNormalStyle(wb);
headCellStyle.setWrapText(true);
cell.setCellStyle(headCellStyle);
cell.setCellValue(column.getFileCol());
}
/*
* HSSFFont font = wb.createFont();
* font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 寬度 //
* font.setItalic(true); //是否使用斜體 // 設置單元格類型 HSSFCellStyle cellStyle
* = wb.createCellStyle(); cellStyle.setFont(font);
* cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 水平佈局:居中
* cellStyle.setWrapText(true);
*/
for(int i=0;i<dataList.size();i++){
HSSFRow dataRow = sheet.createRow(1+i);
Map<String, Object> data = dataList.get(i);
for(int j=0; j<columnList.size(); j++){
ExcelColmnTplConfig column = columnList.get(j);
HSSFCell cell = dataRow.createCell(j);
cell.setCellValue(MapUtil.getStringValue(data, column.getDbCol()));
// cell.setCellStyle(cellStyle);// 設置單元格樣式
}
}
sheet.autoSizeColumn((short) 0); // 調整第一列寬度
sheet.autoSizeColumn((short) 1); // 調整第二列寬度
sheet.autoSizeColumn((short) 2); // 調整第三列寬度
sheet.autoSizeColumn((short) 3); // 調整第四列寬度
File file = new File(filePath);
logger.info(filePath);
out = new FileOutputStream(file);
wb.write(out);
out.close();
} catch (IOException e) {
logger.error("",e);
throw new RuntimeException("文件寫入異常!"+e.getMessage());
} finally {
out = null;
}
return exportXlsName;
}
}
表格存儲類(列名和映射實體對象對應的字段名)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.javapackage 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<ExcelColmnTplConfig> getColumnList() {
return columnList;
}
public void setColumnList(List<ExcelColmnTplConfig> columnList) {
this.columnList = columnList;
}
private String tableName;
private List<ExcelColmnTplConfig> columnList;
/**
* 導入模板定義名
*/
private String title;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
自定義表格樣式工具類PoiExcelUtils.javapackage 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<String, String> columMap = this.getExcelColumnMap();
List<ExcelColmnTplConfig> columnList = new ArrayList<ExcelColmnTplConfig>();
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<Map<String, Object>> dataList = null; // 此處的null替換成導出的數據即可
// 對應表中的列名和映射的字段名
private Map<String,String> getExcelColumnMap() {
Map<String,String> columMap = new LinkedHashMap<String,String>();
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.javapackage 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