@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; } }
/** * 获取单元格的值 * * @param cell * @return */ public static Object getCellValue(Cell cell) { Object cellValue = null; CellType cellType = cell.getCellTypeEnum();// CellType.forInt(cell.getCellType()); if (cellType == CellType.STRING) { cellValue = cell.getStringCellValue(); } else if (cellType == CellType.NUMERIC) { if (DateUtil.isCellDateFormatted(cell)) { cellValue = cell.getDateCellValue(); } else { cellValue = cell.getNumericCellValue(); } } else if (cellType == CellType.BOOLEAN) { cellValue = cell.getBooleanCellValue(); } else if (cellType == CellType.FORMULA) { cellValue = cell.getCellFormula(); } else if (cellType == CellType.BLANK) { cellValue = ""; } return cellValue; }
/** * 判断是否是日期,若是返回日期字符串,否则返回数字字符串 * * @param value * @param formatIndex * @param formatString * @return */ private String formatRawCellContents(double value, int formatIndex, String formatString) { // Is it a date? if (DateUtil.isADateFormat(formatIndex, formatString)) { if (DateUtil.isValidExcelDate(value)) { Date d = DateUtil.getJavaDate(value); SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S"); return f.format(d); } } String _value = NumberToTextConverter.toText(value); if (_value.indexOf('E') > -1) { //若是科学计数法,则转换为非科学计数法 return new BigDecimal(value).toString(); } return _value; }
public static Object getValueOrEmptyAsObject(FormulaEvaluator evaluator, Cell cell) { final CellValue cellValue = evaluator.evaluate(cell); if (cellValue == null) { return ""; } switch (cellValue.getCellType()) { case Cell.CELL_TYPE_BOOLEAN: return Boolean.valueOf(cellValue.getBooleanValue()); case Cell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(cell)) { return cell.getDateCellValue(); } BigDecimal bd = BigDecimal.valueOf(cell.getNumericCellValue()).setScale(DECIMAL_PRECISION, BigDecimal.ROUND_HALF_UP); return bd.stripTrailingZeros(); case Cell.CELL_TYPE_STRING: return cellValue.getStringValue(); case Cell.CELL_TYPE_ERROR: return "ERRO"; default: return ""; } }
private static Object getCellPrimitiveValue(Cell cell, int cellType) { if (cellType == Cell.CELL_TYPE_NUMERIC) { if (DateUtil.isCellDateFormatted(cell)) { Calendar calendar = GregorianCalendar.getInstance(); calendar.setTime(DateUtil.getJavaDate(cell.getNumericCellValue())); return calendar.getTime(); } else { return DECIMAL_FORMAT.format(cell.getNumericCellValue()); } } else if (cellType == Cell.CELL_TYPE_STRING) { if (StringUtils.hasText(cell.getStringCellValue())) { return cell.getStringCellValue(); } } return null; }
public String getStringValue(Cell cell) { if (cell == null) { return null; } switch (cell.getCellType()) { case Cell.CELL_TYPE_STRING: return cell.getStringCellValue(); case Cell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(cell)) { SimpleDateFormat format = new SimpleDateFormat("yyyy'-'MM'-'dd"); return format.format(cell.getDateCellValue()); } return Double.toString(cell.getNumericCellValue()); case Cell.CELL_TYPE_BOOLEAN: return Boolean.toString(cell.getBooleanCellValue()); case Cell.CELL_TYPE_FORMULA: return getStringFormulaValue(cell); case Cell.CELL_TYPE_BLANK: return getStringRangeValue(cell); default: System.out.println(cell.getCellType()); return null; } }
private Object getCellValue(Cell cellObject) { Object cellValue = null; if (cellObject != null) { switch (cellObject.getCellType()) { case HSSFCell.CELL_TYPE_BOOLEAN: cellValue = cellObject.getBooleanCellValue(); break; case HSSFCell.CELL_TYPE_STRING: cellValue = cellObject.getStringCellValue(); break; case HSSFCell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(cellObject)) { cellValue = cellObject.getDateCellValue(); } else { cellValue = cellObject.getNumericCellValue(); } break; default: break; } } return cellValue; }
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; }
private String getCellString(Cell cell, boolean checkIfDate) { if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK) { if (checkIfDate && cell.getCellType() != Cell.CELL_TYPE_STRING && DateUtil.isCellDateFormatted(cell)) { Date date = cell.getDateCellValue(); return df.format(date); } else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) { String str = NumberToTextConverter.toText(cell.getNumericCellValue()); if (str != null) str = str.replace(".", ","); return getStr(str); } else { cell.setCellType(Cell.CELL_TYPE_STRING); return getStr(cell.getStringCellValue()); } } return null; }
@Test public 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(val, "1998-05-02t00:00"); }
/** * POIのDateUtilにあるメソッドが日本語を含む日付書式を正しく扱ってくれないので自力実装 */ public static boolean isCellDateFormatted(Cell cell, double d) { if (cell == null) { return false; } boolean bDate = false; if (DateUtil.isValidExcelDate(d)) { CellStyle style = cell.getCellStyle(); if (style == null) { return false; } int i = style.getDataFormat(); String f = style.getDataFormatString(); bDate = isADateFormat(i, f); } return bDate; }
public FormattedValue formatCellValue(Cell cell, FormulaEvaluator evaluator) { FormattedValue ret = doFormatCellValue(cell, evaluator); if (cell != null && cell.getCellType() == Cell.CELL_TYPE_FORMULA) { ret.setFormula(cell.getCellFormula()); } if (DEBUG && cell != null && cell.getCellStyle() != null) { int cellType = cell.getCellType(); if (cellType == Cell.CELL_TYPE_FORMULA) { cellType = cell.getCachedFormulaResultType(); } if (cellType == Cell.CELL_TYPE_NUMERIC) { System.out.println("Format: " + cell.getCellStyle().getDataFormat() + ": " + cell.getCellStyle().getDataFormatString() + " --- " + ExcelUtils.isCellDateFormatted(cell) + ":" + DateUtil.isCellDateFormatted(cell) + ":" + DateUtil.isInternalDateFormat(cell.getCellStyle().getDataFormat()) + " --- " + ret); } } return ret; }
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 Date d = DateUtil.getJavaDate(serialDate, false); Calendar c = new GregorianCalendar(); c.setTime(d); int result = c.get(_dateFieldId); // Month is a special case due to C semantics if (_dateFieldId == Calendar.MONTH) { result++; } return result; }
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; } }
@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)); } }
/** 从表格之中读取数据并进行处理 * @param fieldInfo * @param cell 当前cell * @return * @throws Exception */ public static Object getValue(ImportFieldInfo fieldInfo, Cell cell) throws Exception{ int size = fieldInfo.getTypeChain().size(); Class<?> type = fieldInfo.getTypeChain().get(size - 1); String dateFormat = fieldInfo.getDateFormat(); int cellType = cell.getCellType(); Object obj = null ; switch (cellType) { case Cell.CELL_TYPE_BLANK: return null; case Cell.CELL_TYPE_BOOLEAN: obj = cell.getBooleanCellValue(); break; case Cell.CELL_TYPE_STRING: obj = cell.getStringCellValue(); break; case Cell.CELL_TYPE_NUMERIC: if(DateUtil.isCellDateFormatted(cell)){ obj = DateUtil.getJavaDate(cell.getNumericCellValue()); }else if(Number.class.isAssignableFrom(type) || ClassUtils.isBaseNumberType(type)){ //当pojo字段类型是数字型时以数字形式获取 obj = cell.getNumericCellValue(); }else{ //其他类型都以string获取 obj = DATA_FORMATTER.formatCellValue(cell); } break; case Cell.CELL_TYPE_ERROR: return null; } if(fieldInfo.getImportProcessor() != null){ obj = fieldInfo.getImportProcessor().process(obj); } obj = ConvertUtils.convertIfNeccesary(obj, type, dateFormat); return obj; }
/** * @param cell * @return */ private String dateOrNumberProcessing(Cell cell) { String txt; if (DateUtil.isCellDateFormatted(cell)) { final DateFormat formatter = new SimpleDateFormat(Constants.DATE_FORMAT); txt = String.valueOf(formatter.format(cell.getDateCellValue())); logger.debug("CELL_TYPE_NUMERIC (date): {}", txt); } else { txt = String.valueOf(cell.getNumericCellValue()); logger.debug("CELL_TYPE_NUMERIC: {}", txt); } return txt; }
@SuppressWarnings("deprecation") private Object getValue(Cell raw, String fieldType) throws CellParsingException { switch (raw.getCellType()) { case Cell.CELL_TYPE_BOOLEAN: return raw.getBooleanCellValue(); case Cell.CELL_TYPE_STRING: { String s = raw.getStringCellValue(); String boolString = s.toLowerCase(); if (boolString.equals("yes")) return true; if (boolString.equals("no")) return false; return s; } case Cell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(raw)) { Date date = raw.getDateCellValue(); return LocalDate.of(date.getYear() + 1900, date.getMonth() + 1, date.getDate()); } return (int) raw.getNumericCellValue(); // formula parsing doesnot work // can be done using FormulaEvaluater case Cell.CELL_TYPE_FORMULA: return true; case Cell.CELL_TYPE_BLANK: { return getInstance(fieldType); } } return null; }
/** * 获取指定单元格的值 * * @param rowNumber 行数,从1开始 * @param cellNumber 列数,从1开始 * @return 该单元格的值 */ public String getCellValue(int rowNumber, int cellNumber) { String result; checkRowAndCell(rowNumber, cellNumber); Sheet sheet = this.workbook.getSheet(this.sheetName); Row row = sheet.getRow(--rowNumber); Cell cell = row.getCell(--cellNumber); switch (cell.getCellTypeEnum()) { case BLANK: result = cell.getStringCellValue(); break; case BOOLEAN: result = String.valueOf(cell.getBooleanCellValue()); break; case ERROR: result = String.valueOf(cell.getErrorCellValue()); break; case FORMULA: result = cell.getCellFormula(); break; case NUMERIC: if (DateUtil.isCellDateFormatted(cell)) { result = format.format(cell.getDateCellValue()); } else { result = String.valueOf(cell.getNumericCellValue()); } break; case STRING: result = cell.getRichStringCellValue().getString(); break; default: result = cell.getStringCellValue(); break; } return result; }
/** * Helper method to determine the output types based on the explicit type given as attribute in "cell" element * and the type through "style" definition. * @param type Value of attribute type {@link ExcelUtil#TYPE} on cell. * @param style Value of attribute style {@link ExcelUtil#STYLE} on cell. */ private void determineOutputTypes(String type, String style) { // Determine the type from attribute valueTypeFromAttribute = MinorType.FLOAT8; if (type != null) { if (TYPE_MAP.containsKey(type)) { valueTypeFromAttribute = TYPE_MAP.get(type); } } valueTypeFromStyle = MinorType.FLOAT8; if (style != null) { if (styleToTypeCache.containsKey(style)) { valueTypeFromStyle = styleToTypeCache.get(style); return; } int styleId = Integer.valueOf(style); CTXf styleDef = styles.getCellXfAt(styleId); if (styleDef != null) { long numFmtId = styleDef.getNumFmtId(); String format = styles.getNumberFormatAt((short) numFmtId); if (DateUtil.isADateFormat((int) numFmtId, format)) { valueTypeFromStyle = MinorType.TIMESTAMP; } } } styleToTypeCache.put(style, valueTypeFromStyle); }
/** * 根据HSSFCell类型设置数据(简单导入使用) * * @param cell 单元格 * @return 处理后的值 */ private static String getCellFormatValue(Cell cell) { String cellValue; if (cell != null) { // 判断当前Cell的Type switch (cell.getCellType()) { // 如果当前Cell的Type为NUMERIC case Cell.CELL_TYPE_NUMERIC: case Cell.CELL_TYPE_FORMULA: { // 判断当前的cell是否为Date if (DateUtil.isCellDateFormatted(cell)) { // 如果是Date类型则,转化为Data格式 Date date = cell.getDateCellValue(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); cellValue = sdf.format(date); } // 如果是纯数字 else { //避免科学计数 java.text.NumberFormat nf = java.text.NumberFormat.getInstance(); nf.setGroupingUsed(false); // 取得当前Cell的数值 cellValue = String.valueOf(nf.format(cell.getNumericCellValue())); } break; } // 如果当前Cell的Type为STRING case Cell.CELL_TYPE_STRING: // 取得当前的Cell字符串 cellValue = cell.getStringCellValue(); break; // 默认的Cell值 default: cellValue = " "; } } else { cellValue = ""; } return cellValue; }
public void intercepterCellValue(Cell cell, CellWrapper cellWrapper, String interceptor) throws Exception { if (cell == null) { cellWrapper.setValue(null); } else { int cellType = cell.getCellType(); switch (cellType) { case Cell.CELL_TYPE_BLANK: cellWrapper.setValue(null); break; case Cell.CELL_TYPE_BOOLEAN: cellWrapper.setValue(Boolean.valueOf(cell.getBooleanCellValue())); break; case Cell.CELL_TYPE_ERROR: cellWrapper.setValue(cell.getErrorCellValue()); break; case Cell.CELL_TYPE_FORMULA: cellWrapper.setValue(cell.getCellFormula()); break; case Cell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(cell)) { Date date = cell.getDateCellValue(); cellWrapper.setValue(date); } else { cellWrapper.setValue(cell.getNumericCellValue()); } break; case Cell.CELL_TYPE_STRING: cellWrapper.setValue(cell.getStringCellValue()); break; } } logger.debug("before interceptor column number[" + cellWrapper.getColumn() + "] cell value[" + cellWrapper.getValue() + "] cell intercepter[" + interceptor + "]"); this.intercepterCellValue(cellWrapper, interceptor); logger.debug("after interceptor cell value[" + cellWrapper.getValue() + "]"); }
private Map<String, String> getRow(Sheet sheet, int index, Map<Integer, String> columnNames, DataFormatter formatter) { Map<String, String> values = new HashMap<>(); for (Cell cell : sheet.getRow(index)) { String key = columnNames.get(cell.getColumnIndex()); if (key != null) { if (cell.getCellTypeEnum() == CellType.NUMERIC && !DateUtil.isCellDateFormatted(cell)) values.put(key, String.valueOf(cell.getNumericCellValue())); else values.put(key, formatter.formatCellValue(cell)); } } return values; }
/** * retrieves a row as a json object. * * @param titles the titles of the row. * @param row the row to read values from. * @return a jsonobject that maps titles to the column values. */ private JsonObject getRow(String[] titles, Row row) { DataFormatter formatter = new DataFormatter(); JsonObject json = new JsonObject(); int index = 0; for (int i = 0; i < row.getLastCellNum(); i++) { Cell cell = row.getCell(i); Object value = null; if (cell != null) { switch (cell.getCellType()) { case Cell.CELL_TYPE_STRING: value = formatter.formatCellValue(cell); break; case Cell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(cell)) { value = cell.getDateCellValue().toInstant().toString(); } else { value = cell.getNumericCellValue(); } break; } // avoid indexing null or empty string, fails to index rows // when date fields are empty and can lead to mappings being // set up incorrectly if leading rows has missing data. if (value != null && !(value.toString().length() == 0)) { json.put(titles[index], value); } } index++; } return json; }
@Override public void startElement( String uri, String localName, String name, Attributes attributes ) throws SAXException { if ( null != name ) { switch ( name ) { case "row": rownum = Integer.parseInt( attributes.getValue( "r" ) ) - 1; currentrowdata.clear(); break; case "c": // c is a new cell String celltypestr = attributes.getValue( "t" ); celltype = ( formats.containsKey( celltypestr ) ? formats.get( celltypestr ) : Cell.CELL_TYPE_BLANK ); // dates don't always have a type attribute if ( Cell.CELL_TYPE_NUMERIC == celltype || null == celltypestr ) { celltype = Cell.CELL_TYPE_NUMERIC; // check if it's a date String styleidstr = attributes.getValue( "s" ); int styleid = ( null == styleidstr ? 0 : Integer.parseInt( styleidstr ) ); XSSFCellStyle style = styles.getStyleAt( styleid ); int formatIndex = style.getDataFormat(); String formatString = style.getDataFormatString(); isdate = DateUtil.isADateFormat( formatIndex, formatString ); } String colname = attributes.getValue( "r" ); colnum = getColNum( colname.substring( 0, colname.lastIndexOf( Integer.toString( rownum + 1 ) ) ) ); break; case "v": // new value for a cell setReading( true ); resetContents(); break; } } }
public String getContents() { String contents = null; // IllegalStateException occurs , if illegal type defined... switch (cell.getCellType()) { case Cell.CELL_TYPE_BLANK: contents = ""; break; case Cell.CELL_TYPE_BOOLEAN: contents = String.valueOf(cell.getBooleanCellValue()); break; case Cell.CELL_TYPE_ERROR: contents = String.valueOf(cell.getErrorCellValue()); break; case Cell.CELL_TYPE_FORMULA: contents = String.valueOf(cell.getNumericCellValue()); break; case Cell.CELL_TYPE_NUMERIC: 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())); } break; case Cell.CELL_TYPE_STRING: contents = String.valueOf(cell.getStringCellValue()); break; default: contents = ""; break; } return contents; }
/** * 行内のセルをコピーする。 * @param fromRow コピー元。 * @param toRow コピー先。 * */ private void copyCells(final Row fromRow, final Row toRow) { for (int j = 0; j < fromRow.getLastCellNum(); j++) { Cell cell = fromRow.getCell(j); if (cell != null) { Cell toCell = toRow.getCell(j); if (toCell == null) { toCell = toRow.createCell(j); } CellStyle cellstyle = cell.getCellStyle(); toCell.setCellStyle(cellstyle); if (cell.getCellType() == Cell.CELL_TYPE_STRING) { toCell.setCellValue(cell.getRichStringCellValue()); } else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) { if (DateUtil.isCellDateFormatted(cell)) { toCell.setCellValue(cell.getDateCellValue()); } else { toCell.setCellValue(cell.getNumericCellValue()); } } else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) { toCell.setCellFormula(cell.getCellFormula()); } else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) { toCell.setCellValue(cell.getBooleanCellValue()); } } } }
private boolean isDateFormatted(final Cell actualCell) { boolean date = false; try { date = DateUtil.isCellDateFormatted(actualCell); } catch (final IllegalStateException e2) { // Nothing to do -> meaning cell is not date formatted } return date; }
private boolean isCellDateFormatted() { /* * DateUtil.isCellDateFormatted() throws IllegalStateException when cell * is not numeric, so we have to work around this. TODO create SCCSE and * report bug against POI */ org.apache.poi.ss.usermodel.CellType poiType = poiCell.getCellTypeEnum(); if (poiType == org.apache.poi.ss.usermodel.CellType.FORMULA) { poiType = poiCell.getCachedFormulaResultTypeEnum(); } return poiType == org.apache.poi.ss.usermodel.CellType.NUMERIC && DateUtil.isCellDateFormatted(poiCell); }
private String getCellValue(Cell cell) { String cellValue = ""; DataFormatter formatter = new DataFormatter(); if (cell != null) { // 判断当前单元格的格式 switch (cell.getCellType()) { case Cell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(cell)) { cellValue = formatter.formatCellValue(cell); } else { // 双精度 double value = cell.getNumericCellValue(); int intValue = (int) value; cellValue = value - intValue == 0 ? String .valueOf(intValue) : String.valueOf(value); } break; case Cell.CELL_TYPE_STRING: cellValue = cell.getStringCellValue(); break; case Cell.CELL_TYPE_BOOLEAN: cellValue = String.valueOf(cell.getBooleanCellValue()); break; case Cell.CELL_TYPE_FORMULA: cellValue = String.valueOf(cell.getCellFormula()); break; case Cell.CELL_TYPE_BLANK: cellValue = ""; break; case Cell.CELL_TYPE_ERROR: cellValue = ""; break; default: cellValue = cell.toString().trim(); break; } } return cellValue.trim(); }
private static Object getCellValueFromFormula(FormulaEvaluator formulaEvaluator, Cell cell) { try { CellValue cellValue = formulaEvaluator.evaluate(cell); if (cellValue.getCellType() == Cell.CELL_TYPE_NUMERIC) { if (DateUtil.isCellDateFormatted(cell)) { Calendar calendar = GregorianCalendar.getInstance(); calendar.setTime(DateUtil.getJavaDate(cellValue.getNumberValue())); return calendar.getTime(); } else { return DECIMAL_FORMAT.format(cellValue.getNumberValue()); } } else if (cellValue.getCellType() == Cell.CELL_TYPE_STRING) { if (StringUtils.hasText(cellValue.getStringValue())) { return cellValue.getStringValue(); } } } catch (NotImplementedException e) { // If formula use Excel features not implemented in POI (like proper), // we can retrieve the cached value (which may no longer be correct, depending of what you do on your file). FormulaFeature feature = EnumUtils.getEnum(FormulaFeature.class, e.getCause().getMessage()); if (ALLOWED_NOT_IMPLEMENTED_FORMULA_FEATURES.contains(feature)) { return getCellPrimitiveValue(cell, cell.getCachedFormulaResultType()); } else { throw e; } } return null; }
@SuppressWarnings("deprecation") private String getCellValueAsString(Cell cell) { // String cellValue = ""; switch (cell.getCellTypeEnum()) { case BLANK: cellValue = ""; break; case BOOLEAN: cellValue = String.valueOf(cell.getBooleanCellValue()); break; case ERROR: cellValue = "ERROR"; break; case FORMULA: cellValue = cell.getCellFormula(); break; case NUMERIC: if (DateUtil.isCellDateFormatted(cell)) { cellValue = dateFormat.format(cell.getDateCellValue()); } else { cellValue = String.valueOf(cell.getNumericCellValue()); } break; case STRING: cellValue = cell.getStringCellValue(); break; case _NONE: cellValue = "NONE"; break; } return cellValue; }
@Override public void visitCellValueNumeric(Column column, Object source, double value) { TimestampParser parser = getTimestampParser(column); TimeZone tz = parser.getDefaultTimeZone().toTimeZone(); Date date = DateUtil.getJavaDate(value, tz); Timestamp t = Timestamp.ofEpochMilli(date.getTime()); pageBuilder.setTimestamp(column, t); }
/*** * get text value of cell irrespective of its content type * * @param cell * @return */ private String getTextValue(Cell cell) { if (cell == null) { return EMPTY_STRING; } int cellType = cell.getCellType(); if (cellType == Cell.CELL_TYPE_BLANK) { return EMPTY_STRING; } if (cellType == Cell.CELL_TYPE_FORMULA) { cellType = cell.getCachedFormulaResultType(); } if (cellType == Cell.CELL_TYPE_STRING) { return cell.getStringCellValue().trim(); } /* * dates are internally stored as decimal.. */ if (cellType == Cell.CELL_TYPE_NUMERIC) { if (DateUtil.isCellDateFormatted(cell)) { return DateUtility.formatDate(cell.getDateCellValue()); } return NumberFormat.getInstance() .format(cell.getNumericCellValue()); } if (cellType == Cell.CELL_TYPE_BOOLEAN) { if (cell.getBooleanCellValue()) { return "1"; } return "0"; } return EMPTY_STRING; }
/*** * Guess the Exility DataValueType of a cell. Text, Decimal, Date abd * boolean are the types that we infer. Boolean is straightforward. If it is * numeric, we check whether it could be date. In case of formula, we go by * the type of cached result. * * @param cell * @return Best guess of cell type */ private DataValueType getExilityType(Cell cell) { if (cell == null) { return DataValueType.TEXT; } int cellType = cell.getCellType(); if (cellType == Cell.CELL_TYPE_FORMULA) { cellType = cell.getCachedFormulaResultType(); } // dates are internally stored as decimal.. if (cellType == Cell.CELL_TYPE_NUMERIC) { if (DateUtil.isCellDateFormatted(cell)) { return DataValueType.DATE; } return DataValueType.DECIMAL; } if (cellType == Cell.CELL_TYPE_BOOLEAN) { return DataValueType.BOOLEAN; } return DataValueType.TEXT; }
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; }