import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import com.dc.flamingo.context.ContextHolder;
import com.dc.flamingo.tools.dao.WorkdayPlanDao;
import com.dc.flamingo.tools.entity.WorkdayPlan;
/**
* 工作日工具
* @Class Name WorkdayUtils
* @Author lee
* @Create In Jun 16, 2011
*/
public class WorkdayUtils {
private static LogUtils log = LogUtils.getLogUtil(WorkdayUtils.class);
public static final String AM_STARTTIME = "0900"; //工作日上午上班时间
public static final String AM_ENDTIME = "1200"; //工作日上午下班时间
public static final String PM_STARTTIME = "1300"; //工作日下午上班时间
public static final String PM_ENDTIME = "1800"; //工作日下午下班时间
public static final int SATURDAY_OF_WEEK = 7; //星期六对应周内天数
public static final int SUNDAY_OF_WEEK = 1; //星期天对应州内天数
public static final double WORKHOUR = 8; //天工作时间
/**
* 获取两个时间间隔间的工作时长
* @Methods Name getWorkHoursBetweenDates
* @Create In Jun 16, 2011 By lee
* @param startDate 开始时间
* @param endDate 结束时间
* @return double 两个时间间隔工时(小时数)
* @throws ParseException
*/
public static double getWorkHoursBetweenDates(Date startDate, Date endDate){
try{
long startTime = startDate.getTime(); //得到开始的毫秒数
long endTime = endDate.getTime(); //得到结束的毫秒数
long costTimes = endTime-startTime; //得到两个日期的毫秒差
long day = costTimes / 3600000 / 24 + 1;
SimpleDateFormat timeFormatter = new SimpleDateFormat("HHmm");
Date dateAmS = timeFormatter.parse(AM_STARTTIME); //上午上班时间
Date dateAmE = timeFormatter.parse(AM_ENDTIME); //上午下班时间
Date datePmS = timeFormatter.parse(PM_STARTTIME); //下午上班时间
Date datePmE = timeFormatter.parse(PM_ENDTIME); //下午上班时间
Date dateStime = timeFormatter.parse(DateUtils.getTimeStr(startDate)); //传入开始时间
Date dateEtime = timeFormatter.parse(DateUtils.getTimeStr(endDate)); //传入结束时间
Date workStartTime = dateStime; //记录工时开始时间
Date workEndTime = dateEtime; //记录工时结束时间
//确认开始时间
if ((dateAmS.getTime() - dateStime.getTime()) >= 0) { //如果传入时间比上班时间早
workStartTime = dateAmS; //工作开始时间记录为上班开始时间
} else if (dateAmS.getTime() < dateStime.getTime()
&& dateStime.getTime() <= dateAmE.getTime()) { //如果传入时间在上午上班时间内
workStartTime = dateStime; //工作开始时间记录为传入时间
} else if (dateAmE.getTime() < dateStime.getTime()
&& dateStime.getTime() <= datePmS.getTime()) { //如果传入时间在午休时间内
workStartTime = datePmS; //工作开始时间记录为下午上班时间
} else if (datePmS.getTime() < dateStime.getTime()
&& dateStime.getTime() < datePmE.getTime()) { //如果传入时间在下午上班时间内
workStartTime = dateStime; //工作开始时间记录为传入时间
} else if (datePmE.getTime() <= dateStime.getTime()) { //如果传入时间为下午下班后
workStartTime = datePmE;
}
// 确定结束时间
if ((dateAmS.getTime() - dateEtime.getTime()) >= 0) { //如果传入时间比上班时间早
workEndTime = dateAmS;
} else if (dateAmS.getTime() < dateEtime.getTime()
&& dateEtime.getTime() <= dateAmE.getTime()) { //如果传入时间在上午上班时间内
workEndTime = dateEtime;
} else if (dateAmE.getTime() < dateEtime.getTime()
&& dateEtime.getTime() <= datePmS.getTime()) { //如果传入时间在午休时间内
workEndTime = datePmS;
} else if (datePmS.getTime() < dateEtime.getTime()
&& dateEtime.getTime() < datePmE.getTime()) { //如果传入时间在下午上班时间内
workEndTime = dateEtime;
} else if (datePmE.getTime() <= dateEtime.getTime()) { //如果传入时间为下午下班后
workEndTime = datePmE;
}
if(DateUtils.isTheSameDay(startDate, endDate)){//如果是同一天
if(isHoliday(startDate)){ //如果是工作日
return 0.0;
}else{
if (dateAmE.getTime() >= workStartTime.getTime()
&& workEndTime.getTime() >= datePmS.getTime()) {//如果包括午休时间
return (double)(workEndTime.getTime() - workStartTime.getTime() - (datePmS
.getTime() - dateAmE.getTime()))/1000/60/60;
} else {
return (double)(workEndTime.getTime() - workStartTime.getTime())/1000/60/60;
}
}
}else{//如果不是同一天
double alltime = 0;
for(int i = 0; i < day; i++){
boolean isHoliday = isHoliday(DateUtils.addDays(startDate, i));
if(!isHoliday){
if(i==0){
//第一天时间
if (dateAmE.getTime() >= workStartTime.getTime()) {//如果包括午休时间
alltime =(double) (datePmE.getTime() - workStartTime.getTime() - (datePmS
.getTime() - dateAmE.getTime()))/1000/60/60;
} else {
alltime = (double)(datePmE.getTime() - workStartTime.getTime())/1000/60/60;
}
}else if(i==day-1){
//最后一天时间
if (dateAmE.getTime() >= workStartTime.getTime()) {//如果包括午休时间
alltime =(double) (datePmE.getTime() - workStartTime.getTime() - (datePmS
.getTime() - dateAmE.getTime()))/1000/60/60;
} else {
alltime = (double)(datePmE.getTime() - workStartTime.getTime())/1000/60/60;
}
}else{
alltime+=WORKHOUR;
}
}
}
return alltime;
}
}catch(Exception e){
e.printStackTrace();
log.error("getWorkHoursBetweenDates:"+e);
}
return 0;
}
/**
* 是否是假期
* @Methods Name isHoliday
* @Create In Jun 16, 2011 By lee
* @param date
* @return boolean
*/
public static boolean isHoliday(Date date){
WorkdayPlanDao workDayPlanDao = (WorkdayPlanDao) ContextHolder.getBean("workdayPlanDao");
WorkdayPlan plan = workDayPlanDao.getPalnByDate(DateUtils.getDateStr(date));
if(plan!=null){
if(plan.getWorkFlag().equals(WorkdayPlan.WORKDAY)){//如果是特殊工作日
return false;
}else if(plan.getWorkFlag().equals(WorkdayPlan.HOLIDAY)){//如果是特殊假期
return true;
}
}else{//如果不是工作日维护中的记录
int dayOfWeek = getDayOfWeek(date);
if(dayOfWeek==SATURDAY_OF_WEEK||dayOfWeek==SUNDAY_OF_WEEK){//如果是周六或周日
return true;
}
}
return false;
}
/**
* 返回星期几
* @Methods Name getDayOfWeek
* @Create In Nov 16, 2010 By huzh
* @param date
* @return 1=星期日 7=星期六,其他类推
* @Return int
*/
public static int getDayOfWeek(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
return c.get(Calendar.DAY_OF_WEEK);
}
}
|
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import com.dc.flamingo.core.support.BaseEntity;
/**
* Bean工具类
* @Class Name BeanUtils
* @Author lee
* @Create In May 25, 2011
*/
public class BeanUtils {
/**
* 将Object转为MAP
* @Methods Name objectToMap
* @Create In May 25, 2011 By lee
* @param obj
* @return Map<String,Object>
*/
@SuppressWarnings("rawtypes")
public static Map<String,Object> objectToMap(Object obj){
Map<String, Object> hashMap = new HashMap<String, Object>();
try {
Class c = obj.getClass();
Method m[] = c.getDeclaredMethods();
for (int i = 0; i < m.length; i++) {
if (m[i].getName().indexOf("get") == 0) {
String propertyName = Character.toLowerCase(m[i].getName().charAt(3))
+ m[i].getName().substring(4);
hashMap.put(propertyName, m[i].invoke(obj, new Object[0]));
}
}
} catch (Exception e) {
e.printStackTrace();
}
return hashMap;
}
/**
* 将Object转为JSON使用的MAP
* @Methods Name objectToJsonMap
* @Create In May 25, 2011 By lee
* @param obj
* @return Map<String,Object>
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static Map<String,Object> objectToJsonMap(Object obj){
if(obj instanceof java.util.Map){
return (Map<String, Object>) obj;
}
Map<String, Object> hashMap = new HashMap<String, Object>();
hashMap.put("success", true);//增加成功返回信息
try {
Class c = obj.getClass();
Method m[] = c.getDeclaredMethods();
for (int i = 0; i < m.length; i++) {
if (m[i].getName().indexOf("get")==0) {
String propertyName = Character.toLowerCase(m[i].getName().charAt(3)) + m[i].getName().substring(4);
Object propertyVlaue = m[i].invoke(obj, new Object[0]);
if(propertyVlaue!=null&&propertyVlaue instanceof BaseEntity){
BaseEntity be = (BaseEntity) propertyVlaue;
hashMap.put(propertyName+"", be.getId());
hashMap.put(propertyName+"_text", be.toString());
}else if(propertyVlaue instanceof Date){//如果是时间格式,格式化
hashMap.put(propertyName, DateUtils.getDateStr((Date) propertyVlaue));
}else if(propertyVlaue instanceof Timestamp){//如果是时间格式,格式化
hashMap.put(propertyName, DateUtils.getTimeStr((Date) propertyVlaue));
}else{
hashMap.put(propertyName, propertyVlaue);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return hashMap;
}
/**
* 请前台传递过来的map,转换成bean
* @param <T>
* @param map
* @param T
* @return
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> T mapToObject(Map<String,Object> map, Class<T> T){
BeanWrapper bw = new BeanWrapperImpl(T);
try{
PropertyDescriptor[] descriptors = bw.getPropertyDescriptors();
for(int i=0;i<descriptors.length;i++){
PropertyDescriptor descriptor = descriptors[i];
String propertyName = descriptor.getName();
Object propertyValue = map.get(propertyName);
if(propertyValue==null||"".equals(propertyValue)){
continue;
}
String propertyValueStr = "";
if(propertyValue instanceof java.lang.Integer || propertyValue instanceof java.lang.Long
|| propertyValue instanceof java.lang.Boolean || propertyValue instanceof java.lang.Float
|| propertyValue instanceof java.lang.Double || propertyValue instanceof java.lang.String
|| propertyValue instanceof java.util.Date){
propertyValueStr = propertyValue.toString();
}
Class propertyTypeClass = descriptor.getPropertyType();
String typeClassName = propertyTypeClass.getName();
if(typeClassName.equals("java.lang.String")) {//如果是字符串类型
bw.setPropertyValue(propertyName, propertyValueStr);
}
else if(typeClassName.equals("int") || typeClassName.equals("java.lang.Integer")) {//如果是整型
Integer intValue = Integer.valueOf(propertyValueStr);
bw.setPropertyValue(propertyName, intValue);
}
else if(typeClassName.equals("long") || typeClassName.equals("java.lang.Long")) {//如果是长整型
Long longValue = Long.valueOf(propertyValueStr);
bw.setPropertyValue(propertyName, longValue);
}
else if(typeClassName.equals("boolean") || typeClassName.equals("java.lang.Boolean")) {//如果是布尔型
Boolean boolValue = Boolean.valueOf(propertyValueStr);
bw.setPropertyValue(propertyName, boolValue);
}
else if(typeClassName.equals("float") || typeClassName.equals("java.lang.Float")) {//如果是短浮点型
Float floatValue = Float.valueOf(propertyValueStr);
bw.setPropertyValue(propertyName, floatValue);
}
else if(typeClassName.equals("double") || typeClassName.equals("java.lang.Double")) {//如果是长浮点型
Double doubleValue = Double.valueOf(propertyValueStr);
bw.setPropertyValue(propertyName, doubleValue);
}
else if(typeClassName.equals("java.util.Date")) {//如果是日期时间类型
Date dateValue = DateUtils.convertStringToDate(propertyValueStr);
bw.setPropertyValue(propertyName, dateValue);
}
else { //对于关联对象,只通过页面的数值设置关联对象的id属性
if(!"0".equals(propertyValueStr)){
BeanWrapper propertybw = new BeanWrapperImpl(propertyTypeClass);
if(propertybw.isWritableProperty("id")&&!"0".equals(propertyValueStr)){
propertybw.setPropertyValue("id",Long.valueOf(propertyValueStr));
}
try {
bw.setPropertyValue(propertyName, propertybw.getWrappedInstance() );
} catch (RuntimeException e) {
bw.setPropertyValue(propertyName, null);
e.printStackTrace();
}
}else{
bw.setPropertyValue(propertyName, null);
}
}
}
}catch(Exception e){
e.printStackTrace();
}
return (T) bw.getWrappedInstance();
}
}
|
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
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 javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
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;
public class ExcelUtils {
/**
* 生成Excel样式
*
* @param list List<Map<String, Object>>
* @param templateName String 模板名称
* @return returnPath String 返回生成的excel路径
* @throws Exception
*/
public static String exportToExcel(List<Map<String, Object>> mapList,String templateName,String downloadPath)
throws Exception {
Workbook workbook = null;
if (StringUtils.isBlank(templateName)) {
return null;
}
// 获取生成好的excel样式
workbook = getWorkBook(mapList, templateName);
// 生成下载的文件名
downloadPath = downloadPath + getFileName(templateName);
// 服务器上生成下载文件
FileOutputStream out = new FileOutputStream(downloadPath);
out.flush();
workbook.write(out);
out.close();
workbook = null;
return downloadPath;
}
/**
* 生成Excel流文件下载
*
* @param response HttpServletResponse
* @param list List<Map<String, Object>>
* @param templateName String 模板路径+名称
* @throws Exception
*/
public static void exportToStream(HttpServletResponse response, List<Map<String, Object>> mapList,
String templateName)
throws Exception {
// 设置文本类型
response.setContentType("application/x-msdownload");
// 设置生成的Excel文件名称
String fileName = getFileName(templateName);
response.setHeader("Content-Disposition", "attachment;filename="+ fileName +"");
OutputStream baos = response.getOutputStream();
Workbook workbook = getWorkBook(mapList, templateName);;
baos.flush();
workbook.write(baos);
baos.close();
}
/**
* 根据excel中的匹配关系与无序集合生成excel
* @param list List<Map<String, Object>> 数据集合
* @param wb Workbook
* @return Workbook
* @throws IOException
* @throws FileNotFoundException
*/
public static Workbook getWorkBook(List<Map<String, Object>> list, String templateName) {
Workbook workbook = null;
String suffix = templateName.substring(templateName.lastIndexOf(".") + 1, templateName
.length());
// 获取模板存放路径
String filePath = PropertiesUtils.getProperty("flex.flexfile.excel.template", "d:\\");
if (StringUtils.isBlank(filePath)) {
return null;
} else {
filePath = filePath + templateName;
}
try{
// 根据需要生成的Excel版本来创建Excel工作空间
workbook = "xls".equals(suffix) ? new HSSFWorkbook(new FileInputStream(filePath)) : new XSSFWorkbook(new FileInputStream(filePath));
// 分页处理
int totalCount = list.size();
int pageSize = 65500;
int sheetSum = 0;
if (totalCount % pageSize == 0) {
sheetSum = totalCount / pageSize;
} else {
sheetSum = totalCount / pageSize + 1;
}
// 根据分页情况导出excel
Sheet sheet = null;
// 分页后获取list中的数据
int jj = 0;
for (int ii = 0; ii < sheetSum; ii++) {
// 创建一个和模板相同sheet表
sheet = workbook.cloneSheet(0);
Row formatRow = sheet.getRow(sheet.getLastRowNum());
int cellNum = formatRow.getLastCellNum();
String[] cellkey = new String[cellNum];
CellStyle[] cellStyle = new CellStyle[cellNum];
for (int i = 0; i < cellNum; i++) {
cellkey[i] = formatRow.getCell(i).getStringCellValue();
cellStyle[i] = formatRow.getCell(i).getCellStyle();
}
sheet.removeRow(formatRow);
// 设定每sheet页显示的条数
if (ii == (sheetSum - 1)) {
if ((totalCount % pageSize) < pageSize) {
pageSize = totalCount % pageSize;
}
}
// 像sheet中写入行数据
for (int k = 0; k < pageSize; k++) {
Map<String, Object> dataMap = (Map<String, Object>) list.get(jj++);
Row row = sheet.createRow((short) (sheet.getLastRowNum() + 1));
for (int j = 0; j < cellNum; j++) {
Cell cell = row.createCell(j);
cell.setCellStyle(cellStyle[j]);
if (dataMap.get(cellkey[j]) != null) {
// 判断数据格式
if (dataMap.get(cellkey[j]) instanceof String) {
cell.setCellValue(dataMap.get(cellkey[j])
.toString());
} else {
// 设置数值格式为double
cell.setCellType(4);
cell.setCellValue(Double.parseDouble(dataMap.get(
cellkey[j]).toString()));
}
}
}
}
}
// 删除生成后的excel中的第一个样式模板
workbook.removeSheetAt(0);
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}catch (IOException e){
e.printStackTrace();
return null;
}
return workbook;
}
/**
* 生成返回下载的excel名称
* @param templateName String
* @return
*/
private static String getFileName(String templateName) {
String prefix = "";
String suffix = "";
// 根据文件路径判断后缀名
if (StringUtils.isBlank(templateName)) {
return null;
} else {
// 这里不能用split,防止多个.出现
suffix = templateName.substring(templateName.lastIndexOf(".") + 1, templateName
.length());
prefix = templateName.substring(0, templateName.lastIndexOf("."));
}
long time = new Date().getTime();
prefix = prefix + "_" + time + "." + suffix;
return prefix;
}
/**
* 导入Excel
* @param templateName String 模板名称
* @param impFile String 上传文件名称,默认上传存储的位置是在属性中配置的 flex.flexfile.savepath
* @return
* @throws IOException
*/
public static List<Map<String,Object>> importExcel(String templateName, String impFile) {
Workbook wb = null;
List<Map<String,Object>> returnList = null;
String suffix = templateName.substring(templateName.lastIndexOf(".") + 1, templateName
.length());
// 获取模板存放路径
String filePath = PropertiesUtils.getProperty("flex.flexfile.excel.template", "d:\\");
if (StringUtils.isBlank(filePath)) {
return null;
} else {
filePath = filePath + templateName;
}
try {
// 获取模板的excel格式
wb = "xls".equals(suffix) ? new HSSFWorkbook(new FileInputStream(filePath)) : new XSSFWorkbook(new FileInputStream(filePath));
// 获取模板第一个sheet页
Sheet sheetTemplateRow = wb.getSheetAt(0);
// 获取模板第一个sheet页的样式行
int rowStart = sheetTemplateRow.getLastRowNum();
Row formatRow = sheetTemplateRow.getRow(rowStart);
int cellNum = formatRow.getLastCellNum();
String[] cellkey = new String[cellNum];
// 获取到模板里面的列名
for (int i = 0; i < cellNum; i++) {
cellkey[i] = formatRow.getCell(i).getStringCellValue();
}
int sheetNum = wb.getNumberOfSheets();
returnList = new ArrayList();
// 获取上传文件信息
String impFileSuffix = templateName.substring(templateName.lastIndexOf(".") + 1, templateName
.length());
wb = "xls".equals(impFileSuffix) ? new HSSFWorkbook(new FileInputStream(impFile)) : new XSSFWorkbook(new FileInputStream(impFile));
List list = null;
Map ebMap = null;
for (int i = 0; i <sheetNum; i++) {
Sheet sheetRow = wb.getSheetAt(i);
list = new ArrayList();
ebMap = new HashMap();
Sheet childSheet = wb.getSheetAt(i);
// 取第一行的数据,按照模板样式来
int firstRowNum = rowStart;
int rowNum = childSheet.getLastRowNum();
int cellNums = childSheet.getRow(firstRowNum).getPhysicalNumberOfCells();
Map<String, Object> hashMap = null;
for (int j = firstRowNum; j <= rowNum; j++) {
Row row = childSheet.getRow(j + 1);
hashMap = new HashMap();
if (row != null) {
for (int k = 0; k < cellkey.length; k++) {
if (row.getCell(k).getCellType() == 1) {
hashMap.put(cellkey[k], row.getCell(k).getRichStringCellValue().toString());
} else {
hashMap.put(cellkey[k], row.getCell(k).getNumericCellValue());
}
}
returnList.add(hashMap);
}
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//删除掉上传的文件
}
return returnList;
}
}
|