org.apache.poi.ss.usermodel.DateUtil Java Examples

The following examples show how to use org.apache.poi.ss.usermodel.DateUtil. 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: Excel2007ResultSet.java    From rapidminer-studio with GNU Affero General Public License v3.0 11 votes vote down vote up
@Override
public ValueType getNativeValueType(int columnIndex) throws ParseException {
	Cell cell = getCurrentCell(columnIndex);
	final int type = cell.getCellType();
	if (type == Cell.CELL_TYPE_BLANK) {
		return ValueType.EMPTY;
	} else if (type == Cell.CELL_TYPE_STRING) {
		return ValueType.STRING;
	} else if (type == Cell.CELL_TYPE_NUMERIC) {
		if (DateUtil.isCellDateFormatted(cell)) {
			return ValueType.DATE;
		} else {
			return ValueType.NUMBER;
		}
	} else if (type == Cell.CELL_TYPE_FORMULA) {
		if (cell.getCachedFormulaResultType() == Cell.CELL_TYPE_NUMERIC) {
			return ValueType.NUMBER;
		} else {
			return ValueType.STRING;
		}
	} else {
		return ValueType.STRING;
	}
}
 
Example #2
Source File: WorkdayFunction.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Evaluate for WORKDAY. Given a date, a number of days and a optional date or interval of holidays, determines which date it is past
 * number of parametrized workdays.
 * 
 * @return {@link ValueEval} with date as its value.
 */
public ValueEval evaluate(ValueEval[] args, OperationEvaluationContext ec) {
    if (args.length < 2 || args.length > 3) {
        return ErrorEval.VALUE_INVALID;
    }

    int srcCellRow = ec.getRowIndex();
    int srcCellCol = ec.getColumnIndex();

    double start;
    int days;
    double[] holidays;
    try {
        start = this.evaluator.evaluateDateArg(args[0], srcCellRow, srcCellCol);
        days = (int) Math.floor(this.evaluator.evaluateNumberArg(args[1], srcCellRow, srcCellCol));
        ValueEval holidaysCell = args.length == 3 ? args[2] : null;
        holidays = this.evaluator.evaluateDatesArg(holidaysCell, srcCellRow, srcCellCol);
        return new NumberEval(DateUtil.getExcelDate(WorkdayCalculator.instance.calculateWorkdays(start, days, holidays)));
    } catch (EvaluationException e) {
        return ErrorEval.VALUE_INVALID;
    }
}
 
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: ReadExecutor.java    From tools with MIT License 6 votes vote down vote up
/**
 * Get the value of the cell
 *
 * @param cell       cell
 * @param excelField Excel field of current field
 * @param field      Current field
 * @param gson       Gson
 * @param r          Current row generated row
 * @return value
 */
private Object getValue(R r, Cell cell, Field field, ExcelField excelField, Gson gson) {
    switch (cell.getCellType()) {
        case _NONE:
        case BLANK:
        case ERROR:
            this.allowEmpty(r, field, excelField, cell.getRowIndex(), cell.getColumnIndex());
            break;
        case BOOLEAN:
            return cell.getBooleanCellValue();
        case NUMERIC:
            if (DateUtil.isCellDateFormatted(cell)) {
                return cell.getDateCellValue();
            }
            return gson.fromJson(gson.toJson(cell.getNumericCellValue()), field.getType());
        case FORMULA:
            return gson.fromJson(gson.toJson(cell.getStringCellValue()), field.getType());
        default:
            return cell.getStringCellValue();
    }
    return null;
}
 
Example #5
Source File: ExcelUtil.java    From Leo with Apache License 2.0 6 votes vote down vote up
private String getStrFromCell(Cell cell) {
		String res = "";
		if (null==cell) {
			return "";
		}
//		res=cell.getRichStringCellValue().toString();
		
		switch (cell.getCellType()) {
			case Cell.CELL_TYPE_NUMERIC: // 数字/日期
				if (DateUtil.isCellDateFormatted(cell)){
					res=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(cell.getDateCellValue());
				}else{
					BigDecimal value =  new BigDecimal(cell.getNumericCellValue());
					String str = value.toString(); 
					if(str.contains(".0"))str = str.replace(".0", "");
					res=str;
				}
				break;
			case Cell.CELL_TYPE_STRING: // 字符串
				res = cell.getStringCellValue();
				break;
			case Cell.CELL_TYPE_BOOLEAN: // 布尔
				Boolean booleanValue = cell.getBooleanCellValue();
				res = booleanValue.toString();
				break;
			case Cell.CELL_TYPE_BLANK: // 空值
				res = "";
				break;
			case Cell.CELL_TYPE_FORMULA: // 公式
				res = cell.getCellFormula();
				break;
			case Cell.CELL_TYPE_ERROR: // 故障
				res = "";
				break;
			default:
				System.out.println("未知类型");
				break;
		}
		return res;
	}
 
Example #6
Source File: TestController.java    From Mario with Apache License 2.0 6 votes vote down vote up
private Object setCellValue(Cell cell) {
    switch (cell.getCellType()) {
        case Cell.CELL_TYPE_STRING:
            return cell.getRichStringCellValue().getString();
        case Cell.CELL_TYPE_NUMERIC:
            if (DateUtil.isCellDateFormatted(cell)) {
                return cell.getDateCellValue();
            } else {
                return cell.getNumericCellValue();
            }
        case Cell.CELL_TYPE_BOOLEAN:
            return cell.getBooleanCellValue();
        case Cell.CELL_TYPE_FORMULA:
            return cell.getCellFormula();
        default:
            System.out.println();
            return "";
    }
}
 
Example #7
Source File: XlsxReader.java    From tablesaw with Apache License 2.0 6 votes vote down vote up
private Boolean isBlank(Cell cell) {
  switch (cell.getCellType()) {
    case STRING:
      if (cell.getRichStringCellValue().length() > 0) {
        return false;
      }
      break;
    case NUMERIC:
      if (DateUtil.isCellDateFormatted(cell)
          ? cell.getDateCellValue() != null
          : cell.getNumericCellValue() != 0) {
        return false;
      }
      break;
    case BOOLEAN:
      if (cell.getBooleanCellValue()) {
        return false;
      }
      break;
    case BLANK:
      return true;
    default:
      break;
  }
  return null;
}
 
Example #8
Source File: StringNumberConverter.java    From easyexcel with Apache License 2.0 6 votes vote down vote up
@Override
public String convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
    GlobalConfiguration globalConfiguration) {
    // If there are "DateTimeFormat", read as date
    if (contentProperty != null && contentProperty.getDateTimeFormatProperty() != null) {
        return DateUtils.format(
            DateUtil.getJavaDate(cellData.getNumberValue().doubleValue(),
                contentProperty.getDateTimeFormatProperty().getUse1904windowing(), null),
            contentProperty.getDateTimeFormatProperty().getFormat());
    }
    // If there are "NumberFormat", read as number
    if (contentProperty != null && contentProperty.getNumberFormatProperty() != null) {
        return NumberUtils.format(cellData.getNumberValue(), contentProperty);
    }
    // Excel defines formatting
    if (cellData.getDataFormat() != null && !StringUtils.isEmpty(cellData.getDataFormatString())) {
        return NumberDataFormatterUtils.format(cellData.getNumberValue().doubleValue(), cellData.getDataFormat(),
            cellData.getDataFormatString(), globalConfiguration);
    }
    // Default conversion number
    return NumberUtils.format(cellData.getNumberValue(), contentProperty);
}
 
Example #9
Source File: DataFormatTest.java    From easyexcel with Apache License 2.0 6 votes vote down vote up
@Test
public void test() throws Exception {
    File file = new File("D:\\test\\dataformat.xlsx");

    List<DataFormatData> list =
        EasyExcel.read(file, DataFormatData.class, null).sheet().headRowNumber(0).doReadSync();
    LOGGER.info("数据:{}", list.size());
    for (DataFormatData data : list) {
        Integer dataFormat = data.getDate().getDataFormat();

        String dataFormatString = data.getDate().getDataFormatString();

        if (dataFormat == null || dataFormatString == null) {

        } else {
            LOGGER.info("格式化:{};{}:{}", dataFormat, dataFormatString,
                DateUtil.isADateFormat(dataFormat, dataFormatString));
        }

        LOGGER.info("返回数据:{}", JSON.toJSONString(data));
    }
}
 
Example #10
Source File: DataFormatTest.java    From easyexcel with Apache License 2.0 6 votes vote down vote up
@Test
public void testxls() throws Exception {
    File file = new File("D:\\test\\dataformat.xls");

    List<DataFormatData> list =
        EasyExcel.read(file, DataFormatData.class, null).sheet().headRowNumber(0).doReadSync();
    LOGGER.info("数据:{}", list.size());
    for (DataFormatData data : list) {
        Integer dataFormat = data.getDate().getDataFormat();

        String dataFormatString = data.getDate().getDataFormatString();

        if (dataFormat == null || dataFormatString == null) {

        } else {
            LOGGER.info("格式化:{};{}:{}", dataFormat, dataFormatString,
                DateUtil.isADateFormat(dataFormat, dataFormatString));
        }

        LOGGER.info("返回数据:{}", JSON.toJSONString(data));
    }
}
 
Example #11
Source File: CellFormat.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Fetches the appropriate value from the cell, and returns the result of
 * applying it to the appropriate format.  For formula cells, the computed
 * value is what is used.
 *
 * @param c The cell.
 *
 * @return The result, in a {@link CellFormatResult}.
 */
public CellFormatResult apply(Cell c) {
    switch (ultimateTypeEnum(c)) {
    case BLANK:
        return apply("");
    case BOOLEAN:
        return apply(c.getBooleanCellValue());
    case NUMERIC:
        Double value = c.getNumericCellValue();
        if (getApplicableFormatPart(value).getCellFormatType() == CellFormatType.DATE) {
            if (DateUtil.isValidExcelDate(value)) {
                return apply(c.getDateCellValue(), value);
            } else {
                return apply(INVALID_VALUE_FOR_FORMAT);
            }
        } else {
            return apply(value);
        }
    case STRING:
        return apply(c.getStringCellValue());
    default:
        return apply("?");
    }
}
 
Example #12
Source File: ExcelPOIHelper.java    From tutorials with MIT License 6 votes vote down vote up
private String readCellContent(Cell cell) {
    String content;
    switch (cell.getCellTypeEnum()) {
    case STRING:
        content = cell.getStringCellValue();
        break;
    case NUMERIC:
        if (DateUtil.isCellDateFormatted(cell)) {
            content = cell.getDateCellValue() + "";
        } else {
            content = cell.getNumericCellValue() + "";
        }
        break;
    case BOOLEAN:
        content = cell.getBooleanCellValue() + "";
        break;
    case FORMULA:
        content = cell.getCellFormula() + "";
        break;
    default:
        content = "";
    }
    return content;
}
 
Example #13
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 #14
Source File: CalendarFieldFunction.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private int getCalField(double serialDate) {
   // For some reason, a date of 0 in Excel gets shown
   //  as the non existant 1900-01-00
	if (((int)serialDate) == 0) {
		switch (_dateFieldId) {
			case Calendar.YEAR: return 1900;
			case Calendar.MONTH: return 1;
			case Calendar.DAY_OF_MONTH: return 0;
		}
		// They want time, that's normal
	}

	// TODO Figure out if we're in 1900 or 1904
	// EXCEL functions round up nearly a half second (probably to prevent floating point
	// rounding issues); use UTC here to prevent daylight saving issues for HOUR
	Calendar c = DateUtil.getJavaCalendarUTC(serialDate + 0.4995 / DateUtil.SECONDS_PER_DAY, false);
	int result = c.get(_dateFieldId);
	
	// Month is a special case due to C semantics
	if (_dateFieldId == Calendar.MONTH) {
		result++;
	}
	
	return result;
}
 
Example #15
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 #16
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 #17
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 #18
Source File: CellFormat.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Fetches the appropriate value from the cell, and uses the result, setting
 * the text and color of a label before returning the result.
 *
 * @param label The label to apply to.
 * @param c     The cell.
 *
 * @return The result, in a {@link CellFormatResult}.
 */
public CellFormatResult apply(JLabel label, Cell c) {
    switch (ultimateTypeEnum(c)) {
        case BLANK:
            return apply(label, "");
        case BOOLEAN:
            return apply(label, c.getBooleanCellValue());
        case NUMERIC:
            Double value = c.getNumericCellValue();
            if (getApplicableFormatPart(value).getCellFormatType() == CellFormatType.DATE) {
                if (DateUtil.isValidExcelDate(value)) {
                    return apply(label, c.getDateCellValue(), value);
                } else {
                    return apply(label, INVALID_VALUE_FOR_FORMAT);
                }
            } else {
                return apply(label, value);
            }
        case STRING:
            return apply(label, c.getStringCellValue());
        default:
            return apply(label, "?");
        }
}
 
Example #19
Source File: XlsxReader.java    From tablesaw with Apache License 2.0 6 votes vote down vote up
private Boolean isBlank(Cell cell) {
  switch (cell.getCellType()) {
    case STRING:
      if (cell.getRichStringCellValue().length() > 0) {
        return false;
      }
      break;
    case NUMERIC:
      if (DateUtil.isCellDateFormatted(cell)
          ? cell.getDateCellValue() != null
          : cell.getNumericCellValue() != 0) {
        return false;
      }
      break;
    case BOOLEAN:
      if (cell.getBooleanCellValue()) {
        return false;
      }
      break;
    case BLANK:
      return true;
    default:
      break;
  }
  return null;
}
 
Example #20
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 #21
Source File: StreamingSheetReader.java    From data-prep with Apache License 2.0 5 votes vote down vote up
@Override
public String formatRawCellContents(double value, int formatIndex, String formatString,
        boolean use1904Windowing) {
    // TDP-1656 (olamy) for some reasons poi use date format with only 2 digits for years
    // even the excel data ws using 4 so force the pattern here
    if (DateUtil.isValidExcelDate(value) && StringUtils.countMatches(formatString, "y") == 2) {
        formatString = StringUtils.replace(formatString, "yy", "yyyy");
    }
    if (DateUtil.isValidExcelDate(value) && StringUtils.countMatches(formatString, "Y") == 2) {
        formatString = StringUtils.replace(formatString, "YY", "YYYY");
    }
    return super.formatRawCellContents(value, formatIndex, formatString, use1904Windowing);

}
 
Example #22
Source File: CellFormat.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the result of applying the format to the given value.  If the
 * value is a number (a type of {@link Number} object), the correct number
 * format type is chosen; otherwise it is considered a text object.
 *
 * @param value The value
 *
 * @return The result, in a {@link CellFormatResult}.
 */
public CellFormatResult apply(Object value) {
    if (value instanceof Number) {
        Number num = (Number) value;
        double val = num.doubleValue();
        if (val < 0 &&
                ((formatPartCount == 2
                        && !posNumFmt.hasCondition() && !negNumFmt.hasCondition())
                || (formatPartCount == 3 && !negNumFmt.hasCondition())
                || (formatPartCount == 4 && !negNumFmt.hasCondition()))) {
            // The negative number format has the negative formatting required,
            // e.g. minus sign or brackets, so pass a positive value so that
            // the default leading minus sign is not also output
            return negNumFmt.apply(-val);
        } else {
            return getApplicableFormatPart(val).apply(val);
        }
    } else if (value instanceof java.util.Date) {
        // Don't know (and can't get) the workbook date windowing (1900 or 1904)
        // so assume 1900 date windowing
        Double numericValue = DateUtil.getExcelDate((Date) value);
        if (DateUtil.isValidExcelDate(numericValue)) {
            return getApplicableFormatPart(numericValue).apply(value);
        } else {
            throw new IllegalArgumentException("value " + numericValue + " of date " + value + " is not a valid Excel date");
        }
    } else {
        return textFmt.apply(value);
    }
}
 
Example #23
Source File: YearFrac.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private static double evaluateDateArg(ValueEval arg, int srcCellRow, int srcCellCol) throws EvaluationException {
	ValueEval ve = OperandResolver.getSingleValue(arg, srcCellRow, (short) srcCellCol);

	if (ve instanceof StringEval) {
		String strVal = ((StringEval) ve).getStringValue();
		Double dVal = OperandResolver.parseDouble(strVal);
		if (dVal != null) {
			return dVal.doubleValue();
		}
		Calendar date = DateParser.parseDate(strVal);
		return DateUtil.getExcelDate(date, false);
	}
	return OperandResolver.coerceValueToDouble(ve);
}
 
Example #24
Source File: Ssio.java    From sep4j with Apache License 2.0 5 votes vote down vote up
/**
 * read the cell. it only supports: boolean, numeric, date(numeric cell type
 * + date cell format) and string.
 *
 * @param cell
 *            the cell to read
 * @return the date if it is a date cell, or else the string value (will be
 *         trimmed to null) . <br/>
 *
 *
 */
static Object readCellAsStringOrDate(Cell cell) {
	if (cell == null) {
		return null;
	}

	if (cell.getCellType() == Cell.CELL_TYPE_BLANK) {
		return null;
	}

	if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
		return String.valueOf(cell.getBooleanCellValue());
	}

	if (cell.getCellType() == Cell.CELL_TYPE_ERROR) {
		return null;
	}

	if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
		return null;
	}

	if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
		if (DateUtil.isCellDateFormatted(cell)) {
			return cell.getDateCellValue();
		} else {
			double v = cell.getNumericCellValue();
			return String.valueOf(v);
		}
	}

	if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
		String s = cell.getStringCellValue();
		return StringUtils.trimToNull(s);
	}
	return null;

}
 
Example #25
Source File: Today.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public ValueEval evaluate(int srcRowIndex, int srcColumnIndex) {
	Calendar now = LocaleUtil.getLocaleCalendar();
	now.clear(Calendar.HOUR);
       now.set(Calendar.HOUR_OF_DAY,0);
	now.clear(Calendar.MINUTE);
	now.clear(Calendar.SECOND);
	now.clear(Calendar.MILLISECOND);
	return new NumberEval(DateUtil.getExcelDate(now.getTime()));
}
 
Example #26
Source File: Cells.java    From datacollector with Apache License 2.0 5 votes vote down vote up
static Field parseCell(Cell cell, FormulaEvaluator evaluator) throws ExcelUnsupportedCellTypeException {
  CellType cellType = cell.getCellTypeEnum();
  // set the cellType of a formula cell to its cached formula result type in order to process it as its result type
  boolean isFormula = cell.getCellTypeEnum().equals(CellType.FORMULA);
  if (isFormula) {
    cellType = cell.getCachedFormulaResultTypeEnum();
  }

  switch (cellType) {
    case STRING:
      return Field.create(cell.getStringCellValue());
    case NUMERIC:
      Double rawValue = cell.getNumericCellValue();  // resolves formulas automatically and gets value without cell formatting
      String displayValue = isFormula ? evaluator.evaluate(cell).formatAsString() : dataFormatter.formatCellValue(cell);
      boolean numericallyEquivalent = false;
      try {
        numericallyEquivalent = Double.parseDouble(displayValue) == rawValue;
      } catch (NumberFormatException e) { }

      if (DateUtil.isCellDateFormatted(cell)) {
        // It's a date, not a number
        java.util.Date dt = cell.getDateCellValue();
        // if raw number is < 1 then it's a time component only, otherwise date.
        return rawValue < 1 ? Field.createTime(dt) : Field.createDate(dt);
      }

      // some machinations to handle integer values going in without decimal vs. with .0 for rawValue
      return Field.create(numericallyEquivalent ? new BigDecimal(displayValue) : BigDecimal.valueOf(rawValue));

    case BOOLEAN:
      return Field.create(cell.getBooleanCellValue());
    case BLANK:
      return Field.create("");
    default:
      throw new ExcelUnsupportedCellTypeException(cell, cellType);
  }
}
 
Example #27
Source File: AbstractExcelExtractor.java    From wandora with GNU General Public License v3.0 5 votes vote down vote up
protected String getCellValueAsString(Cell cell, int type) {
    if(cell != null) {
        switch(type) {
            case Cell.CELL_TYPE_ERROR: {
                return "ERROR"+cell.getErrorCellValue();
            }
            case Cell.CELL_TYPE_BOOLEAN: {
                return ""+cell.getBooleanCellValue();
            }
            case Cell.CELL_TYPE_NUMERIC: {
                if(DateUtil.isCellDateFormatted(cell)) {
                    return dateFormat.format(cell.getDateCellValue());
                }
                else {
                    double value = cell.getNumericCellValue();
                    String formatString = cell.getCellStyle().getDataFormatString();
                    int formatIndex = cell.getCellStyle().getDataFormat();
                    return formatter.formatRawCellContents(value, formatIndex, formatString);
                }
            }
            case Cell.CELL_TYPE_STRING: {
                return cell.getRichStringCellValue().getString();
            }
        }
    }
    return null;
}
 
Example #28
Source File: StreamingSheetReader.java    From components with Apache License 2.0 5 votes vote down vote up
@Override
public String formatRawCellContents(double value, int formatIndex, String formatString, boolean use1904Windowing) {
    // TDP-1656 (olamy) for some reasons poi use date format with only 2 digits for years
    // even the excel data ws using 4 so force the pattern here
    if ( DateUtil.isValidExcelDate( value) && StringUtils.countMatches( formatString, "y") == 2) {
        formatString = StringUtils.replace(formatString, "yy", "yyyy");
    }
    if (DateUtil.isValidExcelDate(value) && StringUtils.countMatches(formatString, "Y") == 2) {
        formatString = StringUtils.replace(formatString, "YY", "YYYY");
    }
    return super.formatRawCellContents(value, formatIndex, formatString, use1904Windowing);

}
 
Example #29
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 #30
Source File: XssfWCellImpl.java    From xlsbeans with Apache License 2.0 5 votes vote down vote up
private String getNumericContents(Cell cell) {
  String contents = null;
  if (DateUtil.isCellDateFormatted(cell)) {
    Date date = cell.getDateCellValue();
    // FIXME format string...in JExcel API standard.
    SimpleDateFormat formatter = new SimpleDateFormat("yy/MM/dd");
    contents = formatter.format(date);
  } else {
    contents = String.valueOf(convertDoubleValue(cell
        .getNumericCellValue()));
  }
  return contents;
}