-
主要步骤
-
导入需要的poi相关依赖
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.17</version>
</dependency>
-
导入处理poi的工具类ExcelImportUtil
public class ExcelImportUtil { //正则表达式 用于匹配属性的第一个字母 private static final String REGEX = "[a-zA-Z]"; /** * 功能: Excel数据导入到数据库 * 参数: originUrl[Excel表的所在路径] * 参数: startRow[从第几行开始] * 参数: endRow[到第几行结束 * (0表示所有行; * 正数表示到第几行结束; * 负数表示到倒数第几行结束)] * 参数: clazz[要返回的对象集合的类型] */ public static List<?> importExcel(String originUrl, int startRow, int endRow, Class<?> clazz) throws IOException { //是否打印提示信息 boolean showInfo = true; return doImportExcel(originUrl, startRow, endRow, showInfo, clazz); } /** * 功能:真正实现导入 */ private static List<Object> doImportExcel(String originUrl, int startRow, int endRow, boolean showInfo, Class<?> clazz) throws IOException { // 判断文件是否存在 File file = new File(originUrl); if (!file.exists()) { throw new IOException("文件名为" + file.getName() + "Excel文件不存在!"); } HSSFWorkbook wb = null; FileInputStream fis = null; List<Row> rowList = new ArrayList<Row>(); try { fis = new FileInputStream(file); // 去读Excel wb = new HSSFWorkbook(fis); Sheet sheet = wb.getSheetAt(0); // 获取最后行号 int lastRowNum = sheet.getLastRowNum(); if (lastRowNum > 0) { // 如果>0,表示有数据 out("\n开始读取名为【" + sheet.getSheetName() + "】的内容:", showInfo); } Row row = null; // 循环读取 for (int i = startRow; i <= lastRowNum + endRow; i++) { row = sheet.getRow(i); if (row != null) { rowList.add(row); out("第" + (i + 1) + "行:", showInfo, false); // 获取每一单元格的值 for (int j = 0; j < row.getLastCellNum(); j++) { String value = getCellValue(row.getCell(j)); if (!value.equals("")) { out(value + " | ", showInfo, false); } } out("", showInfo); } } } catch (IOException e) { e.printStackTrace(); } finally { wb.close(); } return returnObjectList(rowList, clazz); } /** * 功能:获取单元格的值 */ private static String getCellValue(Cell cell) { Object result = ""; if (cell != null) { switch (cell.getCellTypeEnum()) { case STRING: result = cell.getStringCellValue(); break; case NUMERIC: result = cell.getNumericCellValue(); break; case BOOLEAN: result = cell.getBooleanCellValue(); break; case FORMULA: result = cell.getCellFormula(); break; case ERROR: result = cell.getErrorCellValue(); break; case BLANK: break; default: break; } } return result.toString(); } /** * 功能:返回指定的对象集合 */ private static List<Object> returnObjectList(List<Row> rowList, Class<?> clazz) { List<Object> objectList = null; Object obj = null; String attribute = null; String value = null; int j = 0; try { objectList = new ArrayList<Object>(); Field[] declaredFields = clazz.getDeclaredFields(); for (Row row : rowList) { j = 0; obj = clazz.newInstance(); for (Field field : declaredFields) { attribute = field.getName().toString(); value = getCellValue(row.getCell(j)); setAttrributeValue(obj, attribute, value); j++; } objectList.add(obj); } } catch (Exception e) { e.printStackTrace(); } return objectList; } /** * 功能:给指定对象的指定属性赋值 */ private static void setAttrributeValue(Object obj, String attribute, String value) { //得到该属性的set方法名 String method_name = convertToMethodName(attribute, obj.getClass(), true); Method[] methods = obj.getClass().getMethods(); for (Method method : methods) { /** * 因为这里只是调用bean中属性的set方法,属性名称不能重复 * 所以set方法也不会重复,所以就直接用方法名称去锁定一个方法 * (注:在java中,锁定一个方法的条件是方法名及参数) */ if (method.getName().equals(method_name)) { Class<?>[] parameterC = method.getParameterTypes(); try { /**如果是(整型,浮点型,布尔型,字节型,时间类型), * 按照各自的规则把value值转换成各自的类型 * 否则一律按类型强制转换(比如:String类型) */ if (parameterC[0] == int.class || parameterC[0] == java.lang.Integer.class) { value = value.substring(0, value.lastIndexOf(".")); method.invoke(obj, Integer.valueOf(value)); break; } else if (parameterC[0] == float.class || parameterC[0] == java.lang.Float.class) { method.invoke(obj, Float.valueOf(value)); break; } else if (parameterC[0] == double.class || parameterC[0] == java.lang.Double.class) { method.invoke(obj, Double.valueOf(value)); break; } else if (parameterC[0] == byte.class || parameterC[0] == java.lang.Byte.class) { method.invoke(obj, Byte.valueOf(value)); break; } else if (parameterC[0] == boolean.class || parameterC[0] == java.lang.Boolean.class) { method.invoke(obj, Boolean.valueOf(value)); break; } else if (parameterC[0] == java.util.Date.class) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date date = null; try { date = sdf.parse(value); } catch (Exception e) { e.printStackTrace(); } method.invoke(obj, date); break; } else { method.invoke(obj, parameterC[0].cast(value)); break; } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } } } } /** * 功能:根据属性生成对应的set/get方法 */ private static String convertToMethodName(String attribute, Class<?> objClass, boolean isSet) { /** 通过正则表达式来匹配第一个字符 **/ Pattern p = Pattern.compile(REGEX); Matcher m = p.matcher(attribute); StringBuilder sb = new StringBuilder(); /** 如果是set方法名称 **/ if (isSet) { sb.append("set"); } else { /** get方法名称 **/ try { Field attributeField = objClass.getDeclaredField(attribute); /** 如果类型为boolean **/ if (attributeField.getType() == boolean.class || attributeField.getType() == Boolean.class) { sb.append("is"); } else { sb.append("get"); } } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } } /** 针对以下划线开头的属性 **/ if (attribute.charAt(0) != '_' && m.find()) { sb.append(m.replaceFirst(m.group().toUpperCase())); } else { sb.append(attribute); } return sb.toString(); } /** * 功能:输出提示信息(普通信息打印) */ private static void out(String info, boolean showInfo) { if (showInfo) { System.out.print(info + (showInfo ? "\n" : "")); } } /** * 功能:输出提示信息(同一行的不同单元格信息打印) */ private static void out(String info, boolean showInfo, boolean nextLine) { if (showInfo) { if (nextLine) { System.out.print(info + (showInfo ? "\n" : "")); } else { System.out.print(info); } } } }
-
导入处理日期问题的工具类DateUtils(不想导入工具类可截取工具类中使用到的静态方法addDay()和dateToString())
/**
* 描述:公共日期工具类
*/
public class DateUtils {
public static String DATE_FORMAT = "yyyy-MM-dd";
public static String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
public static String DATE_FORMAT_CHINESE = "yyyy年M月d日";
/**
* 获取当前日期
*
* @return
*/
public static String getCurrentDate() {
String datestr = null;
SimpleDateFormat df = new SimpleDateFormat(DateUtils.DATE_FORMAT);
datestr = df.format(new Date());
return datestr;
}
/**
* 获取当前日期时间
*
* @return
*/
public static String getCurrentDateTime() {
String datestr = null;
SimpleDateFormat df = new SimpleDateFormat(DateUtils.DATE_TIME_FORMAT);
datestr = df.format(new Date());
return datestr;
}
/**
* 获取当前日期时间
*
* @return
*/
public static String getCurrentDateTime(String Dateformat) {
String datestr = null;
SimpleDateFormat df = new SimpleDateFormat(Dateformat);
datestr = df.format(new Date());
return datestr;
}
public static String dateToDateTime(Date date) {
String datestr = null;
SimpleDateFormat df = new SimpleDateFormat(DateUtils.DATE_TIME_FORMAT);
datestr = df.format(date);
return datestr;
}
/**
* 将字符串日期转换为日期格式
*
* @param datestr
* @return
*/
public static Date stringToDate(String datestr) {
if (datestr == null || datestr.equals("")) {
return null;
}
Date date = new Date();
SimpleDateFormat df = new SimpleDateFormat(DateUtils.DATE_FORMAT);
try {
date = df.parse(datestr);
} catch (ParseException e) {
date = DateUtils.stringToDate(datestr, "yyyyMMdd");
}
return date;
}
/**
* 将字符串日期转换为日期格式
* 自定義格式
*
* @param datestr
* @return
*/
public static Date stringToDate(String datestr, String dateformat) {
Date date = new Date();
SimpleDateFormat df = new SimpleDateFormat(dateformat);
try {
date = df.parse(datestr);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
/**
* 将日期格式日期转换为字符串格式
*
* @param date
* @return
*/
public static String dateToString(Date date) {
String datestr = null;
SimpleDateFormat df = new SimpleDateFormat(DateUtils.DATE_FORMAT);
datestr = df.format(date);
return datestr;
}
/**
* 将日期格式日期转换为字符串格式 自定義格式
*
* @param date
* @param dateformat
* @return
*/
public static String dateToString(Date date, String dateformat) {
String datestr = null;
SimpleDateFormat df = new SimpleDateFormat(dateformat);
datestr = df.format(date);
return datestr;
}
/**
* 获取日期的DAY值
*
* @param date 输入日期
* @return
*/
public static int getDayOfDate(Date date) {
int d = 0;
Calendar cd = Calendar.getInstance();
cd.setTime(date);
d = cd.get(Calendar.DAY_OF_MONTH);
return d;
}
/**
* 获取日期的MONTH值
*
* @param date 输入日期
* @return
*/
public static int getMonthOfDate(Date date) {
int m = 0;
Calendar cd = Calendar.getInstance();
cd.setTime(date);
m = cd.get(Calendar.MONTH) + 1;
return m;
}
/**
* 获取日期的YEAR值
*
* @param date 输入日期
* @return
*/
public static int getYearOfDate(Date date) {
int y = 0;
Calendar cd = Calendar.getInstance();
cd.setTime(date);
y = cd.get(Calendar.YEAR);
return y;
}
/**
* 获取星期几
*
* @param date 输入日期
* @return
*/
public static int getWeekOfDate(Date date) {
int wd = 0;
Calendar cd = Calendar.getInstance();
cd.setTime(date);
wd = cd.get(Calendar.DAY_OF_WEEK) - 1;
return wd;
}
/**
* 获取输入日期的当月第一天
*
* @param date 输入日期
* @return
*/
public static Date getFirstDayOfMonth(Date date) {
Calendar cd = Calendar.getInstance();
cd.setTime(date);
cd.set(Calendar.DAY_OF_MONTH, 1);
return cd.getTime();
}
/**
* 获得输入日期的当月最后一天
*
* @param date
*/
public static Date getLastDayOfMonth(Date date) {
return DateUtils.addDay(DateUtils.getFirstDayOfMonth(DateUtils.addMonth(date, 1)), -1);
}
/**
* 判断是否是闰年
*
* @param date 输入日期
* @return 是true 否false
*/
public static boolean isLeapYEAR(Date date) {
Calendar cd = Calendar.getInstance();
cd.setTime(date);
int year = cd.get(Calendar.YEAR);
if (year % 4 == 0 && year % 100 != 0 | year % 400 == 0) {
return true;
} else {
return false;
}
}
/**
* 根据整型数表示的年月日,生成日期类型格式
*
* @param year 年
* @param month 月
* @param day 日
* @return
*/
public static Date getDateByYMD(int year, int month, int day) {
Calendar cd = Calendar.getInstance();
cd.set(year, month - 1, day);
return cd.getTime();
}
/**
* 获取年周期对应日
*
* @param date 输入日期
* @param iyear 年数 負數表示之前
* @return
*/
public static Date getYearCycleOfDate(Date date, int iyear) {
Calendar cd = Calendar.getInstance();
cd.setTime(date);
cd.add(Calendar.YEAR, iyear);
return cd.getTime();
}
/**
* 获取月周期对应日
*
* @param date 输入日期
* @param i
* @return
*/
public static Date getMonthCycleOfDate(Date date, int i) {
Calendar cd = Calendar.getInstance();
cd.setTime(date);
cd.add(Calendar.MONTH, i);
return cd.getTime();
}
/**
* 计算 fromDate 到 toDate 相差多少年
*
* @param fromDate
* @param toDate
* @return 年数
*/
public static int getYearByMinusDate(Date fromDate, Date toDate) {
Calendar df = Calendar.getInstance();
df.setTime(fromDate);
Calendar dt = Calendar.getInstance();
dt.setTime(toDate);
return dt.get(Calendar.YEAR) - df.get(Calendar.YEAR);
}
/**
* 计算 fromDate 到 toDate 相差多少个月
*
* @param fromDate
* @param toDate
* @return 月数
*/
public static int getMonthByMinusDate(Date fromDate, Date toDate) {
Calendar df = Calendar.getInstance();
df.setTime(fromDate);
Calendar dt = Calendar.getInstance();
dt.setTime(toDate);
return dt.get(Calendar.YEAR) * 12 + dt.get(Calendar.MONTH) -
(df.get(Calendar.YEAR) * 12 + df.get(Calendar.MONTH));
}
/**
* 计算 fromDate 到 toDate 相差多少天
*
* @param fromDate
* @param toDate
* @return 天数
*/
public static long getDayByMinusDate(Object fromDate, Object toDate) {
Date f = DateUtils.chgObject(fromDate);
Date t = DateUtils.chgObject(toDate);
long fd = f.getTime();
long td = t.getTime();
return (td - fd) / (24L * 60L * 60L * 1000L);
}
/**
* 计算年龄
*
* @param birthday 生日日期
* @param calcDate 要计算的日期点
* @return
*/
public static int calcAge(Date birthday, Date calcDate) {
int cYear = DateUtils.getYearOfDate(calcDate);
int cMonth = DateUtils.getMonthOfDate(calcDate);
int cDay = DateUtils.getDayOfDate(calcDate);
int bYear = DateUtils.getYearOfDate(birthday);
int bMonth = DateUtils.getMonthOfDate(birthday);
int bDay = DateUtils.getDayOfDate(birthday);
if (cMonth > bMonth || (cMonth == bMonth && cDay > bDay)) {
return cYear - bYear;
} else {
return cYear - 1 - bYear;
}
}
/**
* 从身份证中获取出生日期
*
* @param idno 身份证号码
* @return
*/
public static String getBirthDayFromIDCard(String idno) {
Calendar cd = Calendar.getInstance();
if (idno.length() == 15) {
cd.set(Calendar.YEAR, Integer.valueOf("19" + idno.substring(6, 8))
.intValue());
cd.set(Calendar.MONTH, Integer.valueOf(idno.substring(8, 10))
.intValue() - 1);
cd.set(Calendar.DAY_OF_MONTH,
Integer.valueOf(idno.substring(10, 12)).intValue());
} else if (idno.length() == 18) {
cd.set(Calendar.YEAR, Integer.valueOf(idno.substring(6, 10))
.intValue());
cd.set(Calendar.MONTH, Integer.valueOf(idno.substring(10, 12))
.intValue() - 1);
cd.set(Calendar.DAY_OF_MONTH,
Integer.valueOf(idno.substring(12, 14)).intValue());
}
return DateUtils.dateToString(cd.getTime());
}
/**
* 在输入日期上增加(+)或减去(-)天数
*
* @param date 输入日期
* @param iday 要增加或减少的天数
*/
public static Date addDay(Date date, int iday) {
Calendar cd = Calendar.getInstance();
cd.setTime(date);
cd.add(Calendar.DAY_OF_MONTH, iday);
return cd.getTime();
}
/**
* 在输入日期上增加(+)或减去(-)月份
*
* @param date 输入日期
* @param imonth 要增加或减少的月分数
*/
public static Date addMonth(Date date, int imonth) {
Calendar cd = Calendar.getInstance();
cd.setTime(date);
cd.add(Calendar.MONTH, imonth);
return cd.getTime();
}
/**
* 在输入日期上增加(+)或减去(-)年份
*
* @param date 输入日期
* @param iyear 要增加或减少的年数
*/
public static Date addYear(Date date, int iyear) {
Calendar cd = Calendar.getInstance();
cd.setTime(date);
cd.add(Calendar.YEAR, iyear);
return cd.getTime();
}
/**
* 將OBJECT類型轉換為Date
*
* @param date
* @return
*/
public static Date chgObject(Object date) {
if (date != null && date instanceof Date) {
return (Date) date;
}
if (date != null && date instanceof String) {
return DateUtils.stringToDate((String) date);
}
return null;
}
public static long getAgeByBirthday(String date) {
Date birthday = stringToDate(date, "yyyy-MM-dd");
long sec = new Date().getTime() - birthday.getTime();
long age = sec / (1000 * 60 * 60 * 24) / 365;
return age;
}
}
-
解决poi日期问题的方法
/**
* @param time poi中导出的时间(数字)
* @param dateformat 格式化的格式
* @return
*/
static String timeToDate(String time, String dateformat) {
// poi工具类中默认获取到的是1900年到现在的天数,那么就将获取到的天数加上1900年的天数,再转化为日期
Calendar calendar = new GregorianCalendar(1900, 0, -1);
Date d = calendar.getTime();
Date dd = DateUtils.addDay(d, Integer.valueOf(time.substring(0, time.length() - 2)));
return DateUtils.dateToString(dd, dateformat);
}
-
主要代码
public static void main(String[] args) { try { // 第一个参数为excel表格的位置 // 第二个参数为开始解析的行数,初始下标为0 // 第三个参数为结束解析的位置(负数为倒数的行数,0为全部,正数为停止解析的行数) // 第四个参数为解析的目标类(类中属性与表格每一列对应) List<MyArticle> articles = (List<MyArticle>) ExcelImportUtil.importExcel("G:\\milobaldy.xls", 1, 0, MyArticle.class); // 处理Excel表格中各行的时间问题 for (MyArticle article : articles) { System.out.println("处理前的时间为:" + article.time + "\t" + "处理后的时间为:" + timeToDate(article.time, "yyyy/MM/dd")); } } catch (IOException e) { e.printStackTrace(); } }
内容仅供分享,请勿用于商业用途