Java Code Examples for org.apache.poi.ss.usermodel.DateUtil#getJavaDate()

The following examples show how to use org.apache.poi.ss.usermodel.DateUtil#getJavaDate() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BeanSheetReader.java    From xcelite with Apache License 2.0 6 votes vote down vote up
private Object convertToFieldType(Object cellValue, Class<?> fieldType) {
  String value = String.valueOf(cellValue);
  if (fieldType == Double.class || fieldType == double.class) {
    return Double.valueOf(value);
  }
  if (fieldType == Integer.class || fieldType == int.class) {
    return Double.valueOf(value).intValue();
  }
  if (fieldType == Short.class || fieldType == short.class) {
    return Double.valueOf(value).shortValue();
  }
  if (fieldType == Long.class || fieldType == long.class) {
    return Double.valueOf(value).longValue();
  }
  if (fieldType == Float.class || fieldType == float.class) {
    return Double.valueOf(value).floatValue();
  }
  if (fieldType == Character.class || fieldType == char.class) {
    return value.charAt(0);
  }
  if (fieldType == Date.class) {
    return DateUtil.getJavaDate(Double.valueOf(value));
  }
  return value;
}
 
Example 2
Source File: ExcelEntityTest.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
void getNumericDateType() {
  double dateDouble = 35917.0;
  TimeZone utcTimeZone = TimeZone.getTimeZone(ZoneId.of("UTC"));
  Date javaDate = DateUtil.getJavaDate(dateDouble, utcTimeZone);

  when(cell.getCellTypeEnum()).thenReturn(NUMERIC);
  when(cell.getNumericCellValue()).thenReturn(dateDouble);
  when(cell.getDateCellValue()).thenReturn(javaDate);
  CellStyle cellStyle = mock(CellStyle.class);
  when(cell.getCellStyle()).thenReturn(cellStyle);
  short dataFormat = 0x0e;
  when(cellStyle.getDataFormat()).thenReturn(dataFormat);

  Object val = excelEntity.get("attr1");

  assertNotNull(val);
  assertEquals("1998-05-02t00:00", val);
}
 
Example 3
Source File: StaxPoiSheet.java    From hop with Apache License 2.0 6 votes vote down vote up
private Object parseValue( KCellType type, String vContent ) {
  if ( vContent == null ) {
    return null;
  }
  try {
    switch ( type ) {
      case NUMBER:
      case NUMBER_FORMULA:
        return Double.parseDouble( vContent );
      case BOOLEAN:
      case BOOLEAN_FORMULA:
        return vContent.equals( "1" );
      case DATE:
      case DATE_FORMULA:
        Double xlDate = Double.parseDouble( vContent );
        return DateUtil.getJavaDate( xlDate, DATE_TZ );
      case LABEL:
      case STRING_FORMULA:
      case EMPTY:
      default:
        return vContent;
    }
  } catch ( Exception e ) {
    return vContent;
  }
}
 
Example 4
Source File: EDate.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public ValueEval evaluate(ValueEval[] args, OperationEvaluationContext ec) {
    if (args.length != 2) {
        return ErrorEval.VALUE_INVALID;
    }
    try {
        double startDateAsNumber = getValue(args[0]);
        int offsetInMonthAsNumber = (int) getValue(args[1]);

        Date startDate = DateUtil.getJavaDate(startDateAsNumber);
        Calendar calendar = LocaleUtil.getLocaleCalendar();
        calendar.setTime(startDate);
        calendar.add(Calendar.MONTH, offsetInMonthAsNumber);
        return new NumberEval(DateUtil.getExcelDate(calendar.getTime()));
    } catch (EvaluationException e) {
        return e.getErrorEval();
    }
}
 
Example 5
Source File: WorkdayCalculator.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
    * Calculate the workday past x workdays from a starting date, considering a range of holidays.
    *
    * @param start start date.
    * @param workdays number of workdays to be past from starting date.
    * @param holidays an array of holidays.
    * @return date past x workdays.
    */
public Date calculateWorkdays(double start, int workdays, double[] holidays) {
	Date startDate = DateUtil.getJavaDate(start);
	int direction = workdays < 0 ? -1 : 1;
	Calendar endDate = LocaleUtil.getLocaleCalendar();
	endDate.setTime(startDate);
	double excelEndDate = DateUtil.getExcelDate(endDate.getTime());
	while (workdays != 0) {
		endDate.add(Calendar.DAY_OF_YEAR, direction);
		excelEndDate += direction;
		if (endDate.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY
				&& endDate.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY
				&& !isHoliday(excelEndDate,	holidays)) {
			workdays -= direction;
		}
	}
	return endDate.getTime();
}
 
Example 6
Source File: StaxPoiSheet.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
private Object parseValue( KCellType type, String vContent ) {
  if ( vContent == null ) {
    return null;
  }
  try {
    switch ( type ) {
      case NUMBER:
      case NUMBER_FORMULA:
        return Double.parseDouble( vContent );
      case BOOLEAN:
      case BOOLEAN_FORMULA:
        return vContent.equals( "1" );
      case DATE:
      case DATE_FORMULA:
        Double xlDate = Double.parseDouble( vContent );
        return DateUtil.getJavaDate( xlDate, DATE_TZ );
      case LABEL:
      case STRING_FORMULA:
      case EMPTY:
      default:
        return vContent;
    }
  } catch ( Exception e ) {
    return vContent;
  }
}
 
Example 7
Source File: DateNumberConverter.java    From easyexcel with Apache License 2.0 5 votes vote down vote up
@Override
public Date convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
    GlobalConfiguration globalConfiguration) {
    if (contentProperty == null || contentProperty.getDateTimeFormatProperty() == null) {
        return DateUtil.getJavaDate(cellData.getNumberValue().doubleValue(),
            globalConfiguration.getUse1904windowing(), null);
    } else {
        return DateUtil.getJavaDate(cellData.getNumberValue().doubleValue(),
            contentProperty.getDateTimeFormatProperty().getUse1904windowing(), null);
    }
}
 
Example 8
Source File: Serialization.java    From joinery with GNU General Public License v3.0 5 votes vote down vote up
private static final Object readCell(final Cell cell) {
    switch (cell.getCellType()) {
        case NUMERIC:
            if (DateUtil.isCellDateFormatted(cell)) {
                return DateUtil.getJavaDate(cell.getNumericCellValue());
            }
            return cell.getNumericCellValue();
        case BOOLEAN:
            return cell.getBooleanCellValue();
        default:
            return cell.getStringCellValue();
    }
}
 
Example 9
Source File: XlsxResultSet.java    From rapidminer-studio with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Date getDate(int columnIndex) throws ParseException {
	String dateValue = getValue(columnIndex);
	if (dateValue == null) {
		return null;
	}
	switch (getCellType(columnIndex)) {
		case NUMBER:
		case DATE:
			// XLSX stores dates as double values
			double dateAsDouble = Double.parseDouble(dateValue);

			// Use POI methods to convert value to Date java object
			if (DateUtil.isValidExcelDate(dateAsDouble)) {
				return DateUtil.getJavaDate(dateAsDouble, xlsxWorkbook.isDate1904);
			} else {
				throw new ParseException(new ParsingError(getCurrentRow() + 1, columnIndex,
						ParsingError.ErrorCode.UNPARSEABLE_DATE, dateValue));
			}
		case INLINE_STRING:
		case SHARED_STRING:
		case STRING:
			// In case a date is stored as String, we try to parse it here
			String dateString = dateValue;
			try {
				return dateFormatProvider.geDateFormat().parse(dateString);
			} catch (java.text.ParseException e) {
				throw new ParseException(new ParsingError(getCurrentRow() + 1, columnIndex,
						ParsingError.ErrorCode.UNPARSEABLE_DATE, dateString));
			}
		default:
			throw new ParseException(new ParsingError(getCurrentRow() + 1, columnIndex,
					ParsingError.ErrorCode.UNPARSEABLE_DATE, dateValue));

	}
}
 
Example 10
Source File: DateTypeConverter.java    From bdf3 with Apache License 2.0 5 votes vote down vote up
@Override
public Object fromText(Class<?> type, String text) {
	if (StringUtils.isBlank(text)) {
		return null;
	}
	try {
		return DateUtils.parseDate(text, getDateFarmats());
	} catch (ParseException e) {
		try {
			return DateUtil.getJavaDate(Double.valueOf(text));
		} catch (Exception e2) {
			throw new RuntimeException("[" + text + "]无法转换为日期类型。");
		}
	}
}
 
Example 11
Source File: EOMonth.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public ValueEval evaluate(ValueEval[] args, OperationEvaluationContext ec) {
    if (args.length != 2) {
        return ErrorEval.VALUE_INVALID;
    }

    try {
        double startDateAsNumber = NumericFunction.singleOperandEvaluate(args[0], ec.getRowIndex(), ec.getColumnIndex());
        int months = (int) NumericFunction.singleOperandEvaluate(args[1], ec.getRowIndex(), ec.getColumnIndex());

        // Excel treats date 0 as 1900-01-00; EOMONTH results in 1900-01-31
        if (startDateAsNumber >= 0.0 && startDateAsNumber < 1.0) {
            startDateAsNumber = 1.0;
        }

        Date startDate = DateUtil.getJavaDate(startDateAsNumber, false);

        Calendar cal = LocaleUtil.getLocaleCalendar();
        cal.setTime(startDate);
        cal.clear(Calendar.HOUR);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.clear(Calendar.MINUTE);
        cal.clear(Calendar.SECOND);
        cal.clear(Calendar.MILLISECOND);

        cal.add(Calendar.MONTH, months + 1);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        cal.add(Calendar.DAY_OF_MONTH, -1);

        return new NumberEval(DateUtil.getExcelDate(cal.getTime()));
    } catch (EvaluationException e) {
        return e.getErrorEval();
    }
}
 
Example 12
Source File: DataFormatter1.java    From easyexcel with Apache License 2.0 4 votes vote down vote up
private Format getFormat(double cellValue, int formatIndex, String formatStrIn) {
    localeChangedObservable.checkForLocaleChange();

    // Might be better to separate out the n p and z formats, falling back to p when n and z are not set.
    // That however would require other code to be re factored.
    // String[] formatBits = formatStrIn.split(";");
    // int i = cellValue > 0.0 ? 0 : cellValue < 0.0 ? 1 : 2;
    // String formatStr = (i < formatBits.length) ? formatBits[i] : formatBits[0];

    String formatStr = formatStrIn;

    // Excel supports 2+ part conditional data formats, eg positive/negative/zero,
    // or (>1000),(>0),(0),(negative). As Java doesn't handle these kinds
    // of different formats for different ranges, just +ve/-ve, we need to
    // handle these ourselves in a special way.
    // For now, if we detect 2+ parts, we call out to CellFormat to handle it
    // TODO Going forward, we should really merge the logic between the two classes
    if (formatStr.contains(";") && (formatStr.indexOf(';') != formatStr.lastIndexOf(';')
        || rangeConditionalPattern.matcher(formatStr).matches())) {
        try {
            // Ask CellFormat to get a formatter for it
            CellFormat cfmt = CellFormat.getInstance(locale, formatStr);
            // CellFormat requires callers to identify date vs not, so do so
            Object cellValueO = Double.valueOf(cellValue);
            if (DateUtil.isADateFormat(formatIndex, formatStr) &&
            // don't try to handle Date value 0, let a 3 or 4-part format take care of it
                ((Double)cellValueO).doubleValue() != 0.0) {
                cellValueO = DateUtil.getJavaDate(cellValue);
            }
            // Wrap and return (non-cachable - CellFormat does that)
            return new CellFormatResultWrapper(cfmt.apply(cellValueO));
        } catch (Exception e) {
            logger.log(POILogger.WARN, "Formatting failed for format " + formatStr + ", falling back", e);
        }
    }

    // Excel's # with value 0 will output empty where Java will output 0. This hack removes the # from the format.
    if (emulateCSV && cellValue == 0.0 && formatStr.contains("#") && !formatStr.contains("0")) {
        formatStr = formatStr.replaceAll("#", "");
    }

    // See if we already have it cached
    Format format = formats.get(formatStr);
    if (format != null) {
        return format;
    }

    // Is it one of the special built in types, General or @?
    if ("General".equalsIgnoreCase(formatStr) || "@".equals(formatStr)) {
        return generalNumberFormat;
    }

    // Build a formatter, and cache it
    format = createFormat(cellValue, formatIndex, formatStr);
    formats.put(formatStr, format);
    return format;
}
 
Example 13
Source File: ReflectUtils.java    From supplierShop with MIT License 4 votes vote down vote up
/**
 * 直接调用对象方法, 无视private/protected修饰符,
 * 用于一次性调用的情况,否则应使用getAccessibleMethodByName()函数获得Method后反复调用.
 * 只匹配函数名,如果有多个同名函数调用第一个。
 */
@SuppressWarnings("unchecked")
public static <E> E invokeMethodByName(final Object obj, final String methodName, final Object[] args)
{
    Method method = getAccessibleMethodByName(obj, methodName, args.length);
    if (method == null)
    {
        // 如果为空不报错,直接返回空。
        logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + methodName + "] 方法 ");
        return null;
    }
    try
    {
        // 类型转换(将参数数据类型转换为目标方法参数类型)
        Class<?>[] cs = method.getParameterTypes();
        for (int i = 0; i < cs.length; i++)
        {
            if (args[i] != null && !args[i].getClass().equals(cs[i]))
            {
                if (cs[i] == String.class)
                {
                    args[i] = Convert.toStr(args[i]);
                    if (StringUtils.endsWith((String) args[i], ".0"))
                    {
                        args[i] = StringUtils.substringBefore((String) args[i], ".0");
                    }
                }
                else if (cs[i] == Integer.class)
                {
                    args[i] = Convert.toInt(args[i]);
                }
                else if (cs[i] == Long.class)
                {
                    args[i] = Convert.toLong(args[i]);
                }
                else if (cs[i] == Double.class)
                {
                    args[i] = Convert.toDouble(args[i]);
                }
                else if (cs[i] == Float.class)
                {
                    args[i] = Convert.toFloat(args[i]);
                }
                else if (cs[i] == Date.class)
                {
                    if (args[i] instanceof String)
                    {
                        args[i] = DateUtils.parseDate(args[i]);
                    }
                    else
                    {
                        args[i] = DateUtil.getJavaDate((Double) args[i]);
                    }
                }
            }
        }
        return (E) method.invoke(obj, args);
    }
    catch (Exception e)
    {
        String msg = "method: " + method + ", obj: " + obj + ", args: " + args + "";
        throw convertReflectionExceptionToUnchecked(msg, e);
    }
}
 
Example 14
Source File: ReflectUtils.java    From LuckyFrameWeb with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * 直接调用对象方法, 无视private/protected修饰符,
 * 用于一次性调用的情况,否则应使用getAccessibleMethodByName()函数获得Method后反复调用.
 * 只匹配函数名,如果有多个同名函数调用第一个。
 */
@SuppressWarnings("unchecked")
public static <E> E invokeMethodByName(final Object obj, final String methodName, final Object[] args)
{
    Method method = getAccessibleMethodByName(obj, methodName, args.length);
    if (method == null)
    {
        // 如果为空不报错,直接返回空。
        logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + methodName + "] 方法 ");
        return null;
    }
    try
    {
        // 类型转换(将参数数据类型转换为目标方法参数类型)
        Class<?>[] cs = method.getParameterTypes();
        for (int i = 0; i < cs.length; i++)
        {
            if (args[i] != null && !args[i].getClass().equals(cs[i]))
            {
                if (cs[i] == String.class)
                {
                    args[i] = Convert.toStr(args[i]);
                    if (StringUtils.endsWith((String) args[i], ".0"))
                    {
                        args[i] = StringUtils.substringBefore((String) args[i], ".0");
                    }
                }
                else if (cs[i] == Integer.class)
                {
                    args[i] = Convert.toInt(args[i]);
                }
                else if (cs[i] == Long.class)
                {
                    args[i] = Convert.toLong(args[i]);
                }
                else if (cs[i] == Double.class)
                {
                    args[i] = Convert.toDouble(args[i]);
                }
                else if (cs[i] == Float.class)
                {
                    args[i] = Convert.toFloat(args[i]);
                }
                else if (cs[i] == Date.class)
                {
                    if (args[i] instanceof String)
                    {
                        args[i] = DateUtils.parseDate(args[i]);
                    }
                    else
                    {
                        args[i] = DateUtil.getJavaDate((Double) args[i]);
                    }
                }
            }
        }
        return (E) method.invoke(obj, args);
    }
    catch (Exception e)
    {
        String msg = "method: " + method + ", obj: " + obj + ", args: " + Arrays.toString(args) + "";
        throw convertReflectionExceptionToUnchecked(msg, e);
    }
}
 
Example 15
Source File: ExcelUtil.java    From LuckyFrameWeb with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * 获取单元格值
 * 
 * @param row 获取的行
 * @param column 获取单元格列号
 * @return 单元格值
 */
public Object getCellValue(Row row, int column)
{
    if (row == null)
    {
        return null;
    }
    Object val = "";
    try
    {
        Cell cell = row.getCell(column);
        if (cell != null)
        {
            if (cell.getCellTypeEnum() == CellType.NUMERIC)
            {
                val = cell.getNumericCellValue();
                if (HSSFDateUtil.isCellDateFormatted(cell))
                {
                    val = DateUtil.getJavaDate((Double) val); // POI Excel 日期格式转换
                }
                else
                {
                    if ((Double) val % 1 > 0)
                    {
                        val = new DecimalFormat("0.00").format(val);
                    }
                    else
                    {
                        val = new DecimalFormat("0").format(val);
                    }
                }
            }
            else if (cell.getCellTypeEnum() == CellType.STRING)
            {
                val = cell.getStringCellValue();
            }
            else if (cell.getCellTypeEnum() == CellType.BOOLEAN)
            {
                val = cell.getBooleanCellValue();
            }
            else if (cell.getCellTypeEnum() == CellType.ERROR)
            {
                val = cell.getErrorCellValue();
            }

        }
    }
    catch (Exception e)
    {
        return val;
    }
    return val;
}
 
Example 16
Source File: ExcelUtil.java    From ruoyiplus with MIT License 4 votes vote down vote up
/**
 * 获取单元格值
 * 
 * @param row 获取的行
 * @param column 获取单元格列号
 * @return 单元格值
 */
public Object getCellValue(Row row, int column)
{
    if (row == null)
    {
        return row;
    }
    Object val = "";
    try
    {
        Cell cell = row.getCell(column);
        if (cell != null)
        {
            if (cell.getCellTypeEnum() == CellType.NUMERIC)
            {
                val = cell.getNumericCellValue();
                if (HSSFDateUtil.isCellDateFormatted(cell))
                {
                    val = DateUtil.getJavaDate((Double) val); // POI Excel 日期格式转换
                }
                else
                {
                    if ((Double) val % 1 > 0)
                    {
                        val = new DecimalFormat("0.00").format(val);
                    }
                    else
                    {
                        val = new DecimalFormat("0").format(val);
                    }
                }
            }
            else if (cell.getCellTypeEnum() == CellType.STRING)
            {
                val = cell.getStringCellValue();
            }
            else if (cell.getCellTypeEnum() == CellType.BOOLEAN)
            {
                val = cell.getBooleanCellValue();
            }
            else if (cell.getCellTypeEnum() == CellType.ERROR)
            {
                val = cell.getErrorCellValue();
            }

        }
    }
    catch (Exception e)
    {
        return val;
    }
    return val;
}
 
Example 17
Source File: ReflectUtils.java    From frpMgr with MIT License 4 votes vote down vote up
/**
	 * 直接调用对象方法, 无视private/protected修饰符,
	 * 用于一次性调用的情况,否则应使用getAccessibleMethodByName()函数获得Method后反复调用.
	 * 只匹配函数名,如果有多个同名函数调用第一个。
	 */
	public static Object invokeMethodByName(final Object obj, final String methodName, final Object[] args) {
		Method method = getAccessibleMethodByName(obj, methodName, args.length);
		if (method == null) {
			// 如果为空不报错,直接返回空。
//			throw new IllegalArgumentException("在 [" + obj.getClass() + "] 中,没有找到 [" + methodName + "] 方法 ");
			logger.warn("在 [" + obj.getClass() + "] 中,没有找到 [" + methodName + "] 方法 ");
			return null;
		}
		try {
			// 类型转换(将参数数据类型转换为目标方法参数类型)
			Class<?>[] cs = method.getParameterTypes();
			for (int i=0; i<cs.length; i++){
				if (args[i] != null && !args[i].getClass().equals(cs[i])){
					if (cs[i] == String.class){
						args[i] = ObjectUtils.toString(args[i]);
						if(StringUtils.endsWith((String)args[i], ".0")){
							args[i] = StringUtils.substringBefore((String)args[i], ".0");
						}
					}else if (cs[i] == Integer.class){
						args[i] = ObjectUtils.toInteger(args[i]);
					}else if (cs[i] == Long.class){
						args[i] = ObjectUtils.toLong(args[i]);
					}else if (cs[i] == Double.class){
						args[i] = ObjectUtils.toDouble(args[i]);
					}else if (cs[i] == Float.class){
						args[i] = ObjectUtils.toFloat(args[i]);
					}else if (cs[i] == Date.class){
						if (args[i] instanceof String){
							args[i] = DateUtils.parseDate(args[i]);
						}else{
							// POI Excel 日期格式转换
							args[i] = DateUtil.getJavaDate((Double)args[i]);
						}
					}
				}
			}
			return method.invoke(obj, args);
		} catch (Exception e) {
			String msg = "method: "+method+", obj: "+obj+", args: "+args+"";
			throw convertReflectionExceptionToUnchecked(msg, e);
		}
	}
 
Example 18
Source File: ExcelUtil.java    From RuoYi-Vue with MIT License 4 votes vote down vote up
/**
 * 获取单元格值
 * 
 * @param row 获取的行
 * @param column 获取单元格列号
 * @return 单元格值
 */
public Object getCellValue(Row row, int column)
{
    if (row == null)
    {
        return row;
    }
    Object val = "";
    try
    {
        Cell cell = row.getCell(column);
        if (StringUtils.isNotNull(cell))
        {
            if (cell.getCellTypeEnum() == CellType.NUMERIC || cell.getCellTypeEnum() == CellType.FORMULA)
            {
                val = cell.getNumericCellValue();
                if (HSSFDateUtil.isCellDateFormatted(cell))
                {
                    val = DateUtil.getJavaDate((Double) val); // POI Excel 日期格式转换
                }
                else
                {
                    if ((Double) val % 1 > 0)
                    {
                        val = new DecimalFormat("0.00").format(val);
                    }
                    else
                    {
                        val = new DecimalFormat("0").format(val);
                    }
                }
            }
            else if (cell.getCellTypeEnum() == CellType.STRING)
            {
                val = cell.getStringCellValue();
            }
            else if (cell.getCellTypeEnum() == CellType.BOOLEAN)
            {
                val = cell.getBooleanCellValue();
            }
            else if (cell.getCellTypeEnum() == CellType.ERROR)
            {
                val = cell.getErrorCellValue();
            }

        }
    }
    catch (Exception e)
    {
        return val;
    }
    return val;
}
 
Example 19
Source File: ReflectUtils.java    From RuoYi-Vue with MIT License 4 votes vote down vote up
/**
 * 直接调用对象方法, 无视private/protected修饰符,
 * 用于一次性调用的情况,否则应使用getAccessibleMethodByName()函数获得Method后反复调用.
 * 只匹配函数名,如果有多个同名函数调用第一个。
 */
@SuppressWarnings("unchecked")
public static <E> E invokeMethodByName(final Object obj, final String methodName, final Object[] args)
{
    Method method = getAccessibleMethodByName(obj, methodName, args.length);
    if (method == null)
    {
        // 如果为空不报错,直接返回空。
        logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + methodName + "] 方法 ");
        return null;
    }
    try
    {
        // 类型转换(将参数数据类型转换为目标方法参数类型)
        Class<?>[] cs = method.getParameterTypes();
        for (int i = 0; i < cs.length; i++)
        {
            if (args[i] != null && !args[i].getClass().equals(cs[i]))
            {
                if (cs[i] == String.class)
                {
                    args[i] = Convert.toStr(args[i]);
                    if (StringUtils.endsWith((String) args[i], ".0"))
                    {
                        args[i] = StringUtils.substringBefore((String) args[i], ".0");
                    }
                }
                else if (cs[i] == Integer.class)
                {
                    args[i] = Convert.toInt(args[i]);
                }
                else if (cs[i] == Long.class)
                {
                    args[i] = Convert.toLong(args[i]);
                }
                else if (cs[i] == Double.class)
                {
                    args[i] = Convert.toDouble(args[i]);
                }
                else if (cs[i] == Float.class)
                {
                    args[i] = Convert.toFloat(args[i]);
                }
                else if (cs[i] == Date.class)
                {
                    if (args[i] instanceof String)
                    {
                        args[i] = DateUtils.parseDate(args[i]);
                    }
                    else
                    {
                        args[i] = DateUtil.getJavaDate((Double) args[i]);
                    }
                }
            }
        }
        return (E) method.invoke(obj, args);
    }
    catch (Exception e)
    {
        String msg = "method: " + method + ", obj: " + obj + ", args: " + args + "";
        throw convertReflectionExceptionToUnchecked(msg, e);
    }
}
 
Example 20
Source File: ExcelUtil.java    From supplierShop with MIT License 4 votes vote down vote up
/**
 * 获取单元格值
 * 
 * @param row 获取的行
 * @param column 获取单元格列号
 * @return 单元格值
 */
public Object getCellValue(Row row, int column)
{
    if (row == null)
    {
        return row;
    }
    Object val = "";
    try
    {
        Cell cell = row.getCell(column);
        if (cell != null)
        {
            if (cell.getCellTypeEnum() == CellType.NUMERIC || cell.getCellTypeEnum() == CellType.FORMULA)
            {
                val = cell.getNumericCellValue();
                if (HSSFDateUtil.isCellDateFormatted(cell))
                {
                    val = DateUtil.getJavaDate((Double) val); // POI Excel 日期格式转换
                }
                else
                {
                    if ((Double) val % 1 > 0)
                    {
                        val = new DecimalFormat("0.00").format(val);
                    }
                    else
                    {
                        val = new DecimalFormat("0").format(val);
                    }
                }
            }
            else if (cell.getCellTypeEnum() == CellType.STRING)
            {
                val = cell.getStringCellValue();
            }
            else if (cell.getCellTypeEnum() == CellType.BOOLEAN)
            {
                val = cell.getBooleanCellValue();
            }
            else if (cell.getCellTypeEnum() == CellType.ERROR)
            {
                val = cell.getErrorCellValue();
            }

        }
    }
    catch (Exception e)
    {
        return val;
    }
    return val;
}