Java Code Examples for org.apache.poi.ss.usermodel.CellType#NUMERIC

The following examples show how to use org.apache.poi.ss.usermodel.CellType#NUMERIC . 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: ReviewersSheet.java    From tools with Apache License 2.0 8 votes vote down vote up
@SuppressWarnings("deprecation")
	private String validateRow(Row row) {
		for (int i = 0; i < NUM_COLS; i++) {
			Cell cell = row.getCell(i);
			if (REQUIRED[i] && cell == null) {
				return "Required cell "+HEADER_TITLES[i]+" missing for row "+String.valueOf(row.getRowNum())+" in reviewer sheet";
			} else {
				if (i == TIMESTAMP_COL) {
					if (!(cell.getCellTypeEnum() == CellType.NUMERIC)) {
						return "Timestamp cell is not a numeric type for row "+String.valueOf(row.getRowNum())+" in Reviewer sheet";
					}
				}
//				if (cell.getCellType() != Cell.CELL_TYPE_STRING) {
//					return "Invalid cell format for "+HEADER_TITLES[i]+" for forw "+String.valueOf(row.getRowNum());
//				}
			}
		}
		return null;
	}
 
Example 2
Source File: StreamingCell.java    From excel-streaming-reader with Apache License 2.0 7 votes vote down vote up
/**
 * Only valid for formula cells
 * @return one of ({@link CellType#NUMERIC}, {@link CellType#STRING},
 *     {@link CellType#BOOLEAN}, {@link CellType#ERROR}) depending
 * on the cached value of the formula
 */
@Override
public CellType getCachedFormulaResultType() {
  if (formulaType) {
    if(contentsSupplier.getContent() == null || type == null) {
      return CellType.BLANK;
    } else if("n".equals(type)) {
      return CellType.NUMERIC;
    } else if("s".equals(type) || "inlineStr".equals(type) || "str".equals(type)) {
      return CellType.STRING;
    } else if("b".equals(type)) {
      return CellType.BOOLEAN;
    } else if("e".equals(type)) {
      return CellType.ERROR;
    } else {
      throw new UnsupportedOperationException("Unsupported cell type '" + type + "'");
    }
  } else  {
    throw new IllegalStateException("Only formula cells have cached results");
  }
}
 
Example 3
Source File: OriginsSheetV1d2.java    From tools with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
	private String validateRow(Row row) {
		for (int i = 0; i < NUM_COLS; i++) {
			Cell cell = row.getCell(i);
			if (cell == null) {
				if (REQUIRED[i]) {
					return "Required cell "+HEADER_TITLES[i]+" missing for row "+String.valueOf(row.getRowNum()+" in Origins Spreadsheet");
				}
			} else {
				if (i == CREATED_COL) {
					if (!(cell.getCellTypeEnum() == CellType.NUMERIC)) {
						return "Created column in origin spreadsheet is not of type Date";
					}
				}
//				if (cell.getCellType() != Cell.CELL_TYPE_STRING) {
//					return "Invalid cell format for "+HEADER_TITLES[i]+" for forw "+String.valueOf(row.getRowNum());
//				}
			}
		}
		return null;
	}
 
Example 4
Source File: OriginsSheetV2d0.java    From tools with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
private String validateRow(Row row) {
	for (int i = 0; i < NUM_COLS; i++) {
		Cell cell = row.getCell(i);
		if (cell == null) {
			if (REQUIRED[i]) {
				return "Required cell "+HEADER_TITLES[i]+" missing for row "+String.valueOf(row.getRowNum()+" in Origins Spreadsheet");
			}
		} else {
			if (i == CREATED_COL) {
				if (!(cell.getCellTypeEnum() == CellType.NUMERIC)) {
					return "Created column in origin spreadsheet is not of type Date";
				}
			}
		}
	}
	return null;
}
 
Example 5
Source File: StreamingCell.java    From excel-streaming-reader with Apache License 2.0 6 votes vote down vote up
/**
 * Return the cell type.
 *
 * @return the cell type
 */
@Override
public CellType getCellType() {
  if(formulaType) {
    return CellType.FORMULA;
  } else if(contentsSupplier.getContent() == null || type == null) {
    return CellType.BLANK;
  } else if("n".equals(type)) {
    return CellType.NUMERIC;
  } else if("s".equals(type) || "inlineStr".equals(type) || "str".equals(type)) {
    return CellType.STRING;
  } else if("str".equals(type)) {
    return CellType.FORMULA;
  } else if("b".equals(type)) {
    return CellType.BOOLEAN;
  } else if("e".equals(type)) {
    return CellType.ERROR;
  } else {
    throw new UnsupportedOperationException("Unsupported cell type '" + type + "'");
  }
}
 
Example 6
Source File: ForkedEvaluationCell.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public void setValue(ValueEval value) {
	Class<? extends ValueEval> cls = value.getClass();

	if (cls == NumberEval.class) {
		_cellType = CellType.NUMERIC;
		_numberValue = ((NumberEval)value).getNumberValue();
		return;
	}
	if (cls == StringEval.class) {
		_cellType = CellType.STRING;
		_stringValue = ((StringEval)value).getStringValue();
		return;
	}
	if (cls == BoolEval.class) {
		_cellType = CellType.BOOLEAN;
		_booleanValue = ((BoolEval)value).getBooleanValue();
		return;
	}
	if (cls == ErrorEval.class) {
		_cellType = CellType.ERROR;
		_errorValue = ((ErrorEval)value).getErrorCode();
		return;
	}
	if (cls == BlankEval.class) {
		_cellType = CellType.BLANK;
		return;
	}
	throw new IllegalArgumentException("Unexpected value class (" + cls.getName() + ")");
}
 
Example 7
Source File: AccessibilityImporter.java    From TomboloDigitalConnector with MIT License 5 votes vote down vote up
@Override
protected void importDatasource(Datasource datasource, List<String> geographyScope, List<String> temporalScope, List<String> datasourceLocation) throws Exception {
    SubjectType subjectType = SubjectTypeUtils.getOrCreate(AbstractONSImporter.PROVIDER, OaImporter.OaType.lsoa.name(), OaImporter.OaType.lsoa.datasourceSpec.getDescription());
    // Loop over years
    for (int sheetId = 0; sheetId < getWorkbook().getNumberOfSheets(); sheetId++){
        Sheet sheet = getWorkbook().getSheetAt(sheetId);

        int year;
        try {
            year = Integer.parseInt(sheet.getSheetName().substring(sheet.getSheetName().length()-4, sheet.getSheetName().length()));
        }catch (NumberFormatException e){
            // Sheetname does not end in a year
            continue;
        }

        // Create extractors for each timed value
        List<TimedValueExtractor> timedValueExtractors = new ArrayList<>();

        RowCellExtractor subjectExtractor = new RowCellExtractor(0, CellType.STRING);
        ConstantExtractor timestampExtractor = new ConstantExtractor(String.valueOf(year));

        // Get the attribute label row and create TimedValueExtractors
        Row attributeLabelRow = sheet.getRow(5);
        for (int columnId = 0; columnId < attributeLabelRow.getLastCellNum(); columnId++){
            RowCellExtractor tmpAttributeLabelExtractor = new RowCellExtractor(columnId, CellType.STRING);
            tmpAttributeLabelExtractor.setRow(attributeLabelRow);
            Attribute attribute = AttributeUtils.getByProviderAndLabel(getProvider(), tmpAttributeLabelExtractor.extract());
            if (attribute != null){
                ConstantExtractor attributeExtractor = new ConstantExtractor(attribute.getLabel());
                RowCellExtractor valueExtractor = new RowCellExtractor(columnId, CellType.NUMERIC);
                timedValueExtractors.add(new TimedValueExtractor(getProvider(), subjectType, subjectExtractor, attributeExtractor, timestampExtractor, valueExtractor));
            }
        }

        // Extract timed values
        excelUtils.extractAndSaveTimedValues(sheet, this, timedValueExtractors);
    }

    getWorkbook().close();
}
 
Example 8
Source File: XLSFormatter.java    From yarg with Apache License 2.0 5 votes vote down vote up
/**
 * copies template cell to result row into result column. Fills this cell with data from band
 *
 * @param templateCell - template cell
 * @param resultRow    - result row
 * @param resultColumn - result column
 * @param band         - band
 */
private HSSFCell copyCellFromTemplate(HSSFCell templateCell, HSSFRow resultRow, int resultColumn, BandData band) {
    checkThreadInterrupted();
    if (templateCell == null) return null;

    HSSFCell resultCell = resultRow.createCell(resultColumn);

    HSSFCellStyle templateStyle = templateCell.getCellStyle();
    HSSFCellStyle resultStyle = copyCellStyle(templateStyle);
    resultCell.setCellStyle(resultStyle);

    String templateCellValue = "";
    CellType cellType = templateCell.getCellType();

    if (cellType != CellType.FORMULA && cellType != CellType.NUMERIC) {
        HSSFRichTextString richStringCellValue = templateCell.getRichStringCellValue();
        templateCellValue = richStringCellValue != null ? richStringCellValue.getString() : "";

        templateCellValue = extractStyles(templateCell, resultCell, templateCellValue, band);
    }

    if (cellType == CellType.STRING && containsJustOneAlias(templateCellValue)) {
        updateValueCell(rootBand, band, templateCellValue, resultCell,
                drawingPatriarchsMap.get(resultCell.getSheet()));
    } else {
        String cellValue = inlineBandDataToCellString(templateCell, templateCellValue, band);
        setValueToCell(resultCell, cellValue, cellType);
    }

    return resultCell;
}
 
Example 9
Source File: RowCellExtractorTest.java    From TomboloDigitalConnector with MIT License 5 votes vote down vote up
@Test
public void extract() throws Exception {
    RowCellExtractor extractor = new RowCellExtractor(1, CellType.NUMERIC);

    extractor.setRow(workbook.getSheet("sheet").getRow(0));
    assertEquals("5.0", extractor.extract());

    extractor.setRow(workbook.getSheet("sheet").getRow(1));
    assertEquals("6.0", extractor.extract());
}
 
Example 10
Source File: RowCellExtractorTest.java    From TomboloDigitalConnector with MIT License 5 votes vote down vote up
@Test
public void extractSillyValue() throws Exception {

    RowCellExtractor extractor = new RowCellExtractor(3, CellType.NUMERIC);

    extractor.setRow(workbook.getSheet("sheet").getRow(0));
    thrown.expect(BlankCellException.class);
    thrown.expectMessage(new StringStartsWith("Could not extract value"));
    extractor.extract();

    extractor.setRow(workbook.getSheet("sheet").getRow(1));
    assertEquals("7.0", extractor.extract());

}
 
Example 11
Source File: ExcelReaderService.java    From abixen-platform with GNU Lesser General Public License v2.1 5 votes vote down vote up
private String formatIfData(final Cell cell) {
    if (cell.getCellTypeEnum() == CellType.NUMERIC && isCellDateFormatted(cell)) {
        final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return simpleDateFormat.format(cell.getDateCellValue());
    }
    return cell.toString();
}
 
Example 12
Source File: ExcelServiceImpl.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
/**
 * Get the type of a cell, it can be num, date, time or string
 *
 * @param cell
 * @return
 */
public static String getCellType(final Cell cell) {
    final String result;
    final double cellValueNumeric;
    final CellType cellType = cell.getCellType();

    if (cellType == CellType.NUMERIC) {
        cellValueNumeric = cell.getNumericCellValue();

        //date cell, it can be date, time or datetime
        if (DateUtil.isCellDateFormatted(cell)) {
            //time cell
            if (cellValueNumeric < 1) {
                result = "time";
            }
            //date cell
            else {
                result = "date";
            }
        }
        //numeric cell
        else {
            result = "num";
        }
    }
    //String cell
    else {
        result = "string";
    }
    return result;
}
 
Example 13
Source File: FlatFileExtractor.java    From Open-Lowcode with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * provides the number of characters needed for a cell
 * 
 * @param cell the cell to analyze
 * @return number of characters
 */
public static int getCellNbChar(Cell cell) {
	String cellcontentastext = "";
	if (cell.getCellType() == CellType.STRING)
		cellcontentastext = cell.getStringCellValue();
	if (cell.getCellType() == CellType.NUMERIC)
		cellcontentastext = "" + cell.getNumericCellValue();
	return maxNumberCharacter(cellcontentastext);
}
 
Example 14
Source File: ImportDataUtils.java    From opencps-v2 with GNU Affero General Public License v3.0 4 votes vote down vote up
public static JSONObject convertRowToDossier(Row currentRow) {
	JSONObject jsonData = JSONFactoryUtil.createJSONObject();
	try {
		
		CellType typeApp = currentRow.getCell(1).getCellType();
		if (typeApp == CellType.STRING) {
			jsonData.put(DossierTerm.APPLICANT_ID_NO,
					Validator.isNotNull(currentRow.getCell(1).getStringCellValue())
							? currentRow.getCell(1).getStringCellValue().trim()
							: StringPool.BLANK);
			
		} else if(typeApp == CellType.NUMERIC){
			jsonData.put(DossierTerm.APPLICANT_ID_NO, currentRow.getCell(1).getNumericCellValue());
		}
		//jsonData.put(DossierTerm.APPLICANT_ID_NO, currentRow.getCell(1).getStringCellValue().trim());

		jsonData.put(DossierTerm.APPLICANT_NAME, currentRow.getCell(2).getStringCellValue().trim());
		
		String appType = Validator.isNotNull(currentRow.getCell(3).getStringCellValue())
				? currentRow.getCell(3).getStringCellValue().trim()
				: StringPool.BLANK;
		if ("CD".equalsIgnoreCase(appType)) {
			jsonData.put(DossierTerm.APPLICANT_ID_TYPE, "citizen");
		} else if ("DN".equalsIgnoreCase(appType)){
			jsonData.put(DossierTerm.APPLICANT_ID_TYPE, "business");
		} else {
			jsonData.put(DossierTerm.APPLICANT_ID_TYPE, StringPool.BLANK);
		}

		CellType typeDate = currentRow.getCell(4).getCellType();
		if (typeDate == CellType.STRING) {
			
			String strAppIdDate = Validator.isNotNull(currentRow.getCell(4).getStringCellValue())
					? currentRow.getCell(4).getStringCellValue().trim() : StringPool.BLANK;
			Date appIdDate = null;
			if (Validator.isNotNull(strAppIdDate)) {
				SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
				appIdDate = sdf.parse(strAppIdDate);
			}
			//
			jsonData.put(DossierTerm.APPLICANT_ID_DATE, appIdDate != null ? appIdDate.getTime() : 0);
			
		} else if(typeDate == CellType.NUMERIC){
			jsonData.put(DossierTerm.APPLICANT_ID_DATE, currentRow.getCell(4).getNumericCellValue());
		} else if (DateUtil.isCellDateFormatted(currentRow.getCell(4))) {
			jsonData.put(DossierTerm.APPLICANT_ID_DATE,currentRow.getCell(4).getDateCellValue() != null
					? currentRow.getCell(4).getDateCellValue().getTime() : 0);
		}

		//jsonData.put(DossierTerm.APPLICANT_ID_DATE, currentRow.getCell(4).getStringCellValue().trim());
		jsonData.put(DossierTerm.ADDRESS, currentRow.getCell(5).getStringCellValue().trim());
		jsonData.put(DossierTerm.CONTACT_EMAIL, currentRow.getCell(6).getStringCellValue().trim());
		CellType typeTel = currentRow.getCell(7).getCellType();
		if (typeTel == CellType.STRING) {
			jsonData.put(DossierTerm.CONTACT_TEL_NO,
					Validator.isNotNull(currentRow.getCell(7).getStringCellValue())
							? currentRow.getCell(7).getStringCellValue().trim()
							: StringPool.BLANK);
			
		} else if(typeTel == CellType.NUMERIC){
			jsonData.put(DossierTerm.CONTACT_TEL_NO, currentRow.getCell(7).getNumericCellValue());
		}
		//jsonData.put(DossierTerm.CONTACT_TEL_NO, currentRow.getCell(7).getStringCellValue().trim());

	} catch (Exception e) {
		_log.error(e);
	}
	
	return jsonData;
}
 
Example 15
Source File: GetRowIndexByConditionService.java    From cs-actions with Apache License 2.0 4 votes vote down vote up
private static String getRowIndex(final Sheet worksheet,
                                  final int firstRow,
                                  final String input,
                                  final int columnIndex,
                                  final String operator) {
    String result = "";
    double cellValueNumeric;
    String cellFormat;

    double inputNumeric = processValueInput(input);

    for (int i = firstRow; i <= worksheet.getLastRowNum(); i++) {
        Row row = worksheet.getRow(i);
        if (row == null) {
            row = worksheet.createRow(i);
        }
        if (row != null) {
            Cell cell = row.getCell(columnIndex);
            if (cell == null) {
                cell = row.createCell(columnIndex);
            }
            if (cell != null) {
                CellType cellType = cell.getCellType();
                if (cellType != CellType.ERROR) {
                    cellFormat = getCellType(cell);
                    //string comparison
                    if (cellFormat.equalsIgnoreCase("string") && inputFormat.equalsIgnoreCase("string")) {
                        DataFormatter aFormatter = new DataFormatter();
                        String aCellString = aFormatter.formatCellValue(cell);
                        if (compareStringValue(aCellString, input, operator)) {
                            result += i + ",";
                        }
                    }
                    //value input is empty, and the cell in the worksheet is in numeric type
                    else if (!cellFormat.equalsIgnoreCase(inputFormat))
                    //((cellType != CellType.STRING && inputFormat.equalsIgnoreCase("string"))||
                    //(cellType != CellType.NUMERIC && !inputFormat.equalsIgnoreCase("string")))
                    {
                        if (operator.equals("!=")) {
                            result += i + ",";
                        }
                    }

                    //numeric comparison
                    else if (cellType == CellType.NUMERIC && !inputFormat.equalsIgnoreCase("string")) {
                        cellValueNumeric = cell.getNumericCellValue();
                        //both are date or time
                        if ((cellFormat.equalsIgnoreCase("date") && inputFormat.equalsIgnoreCase("date")) ||
                                (cellFormat.equalsIgnoreCase("time") && inputFormat.equalsIgnoreCase("time")) ||
                                (cellFormat.equalsIgnoreCase("num") && inputFormat.equalsIgnoreCase("num"))) {
                            if (compareNumericValue(cellValueNumeric, inputNumeric, operator)) {
                                result += i + ",";
                            }
                        }
                    }
                }
            }
        }
    }
    if (!result.isEmpty()) {
        final int index = result.lastIndexOf(',');
        result = result.substring(0, index);
    }

    return result;
}
 
Example 16
Source File: SpreadsheetReader.java    From taro with MIT License 4 votes vote down vote up
public boolean isNumeric(int col, int row) {
    return getCellType(col, row) == CellType.NUMERIC;
}
 
Example 17
Source File: ExcelHelp.java    From hy.common.report with Apache License 2.0 4 votes vote down vote up
public final static PartitionMap<String ,RCell> readDatas(Sheet i_Sheet ,Integer i_BeginRow ,Integer i_EndRow)
{
    PartitionMap<String ,RCell> v_Ret      = new TablePartition<String ,RCell>();
    Sheet                       v_Sheet    = i_Sheet;
    int                         v_BeginRow = 0;
    int                         v_EndRow   = 0;
    
    if ( i_BeginRow != null )
    {
        v_BeginRow = i_BeginRow.intValue();
        
        if ( v_BeginRow < 0 )
        {
            v_BeginRow = 0;
        }
    }
    
    if ( i_EndRow != null )
    {
        v_EndRow = i_EndRow.intValue();
    }
    else
    {
        v_EndRow = v_Sheet.getLastRowNum();
    }
    
    for (int v_RowNo=v_BeginRow; v_RowNo<=v_EndRow; v_RowNo++)
    {
        Row v_Row = v_Sheet.getRow(v_RowNo);
        if ( v_Row == null )
        {
            continue;
        }
        
        short v_CellCount = v_Row.getLastCellNum();
        
        for (int v_ColumnNo=0; v_ColumnNo<v_CellCount; v_ColumnNo++)
        {
            Cell v_Cell = v_Row.getCell(v_ColumnNo);
            if ( v_Cell == null )
            {
                continue;
            }
            
            if ( v_Cell.getCellTypeEnum() == CellType.STRING )
            {
                String v_Value = v_Cell.getStringCellValue();
                
                if ( !Help.isNull(v_Value) )
                {
                    RCell        v_RCell    = new RCell(v_RowNo ,v_ColumnNo);
                    List<String> v_Decimals = StringHelp.getString(v_Cell.getCellStyle().getDataFormatString() ,$Decimal);
                    if ( !Help.isNull(v_Decimals) )
                    {
                        v_RCell.setDecimal(v_Decimals.get(0).split("\\.")[1].length());
                    }
                    
                    v_Ret.putRow(v_Value ,v_RCell); // 2018-05-07 修复:不再trim()。因为去空格后,原数据格式会被改变,比如说用户就是想导出空格呢?
                                                    //            其二,当为占位符查询时,也是不去空格的查询,这里去空格后,为查询不到匹配的占位符解析信息的。
                }
            }
            else if ( v_Cell.getCellTypeEnum() == CellType.NUMERIC )
            {
                if ( HSSFDateUtil.isCellDateFormatted(v_Cell) ) 
                {
                    if ( v_Cell.getDateCellValue() != null )
                    {
                        v_Ret.putRow((new Date(v_Cell.getDateCellValue())).getFull() ,new RCell(v_RowNo ,v_ColumnNo));
                    }
                } 
                else 
                {
                    v_Ret.putRow(String.valueOf(v_Cell.getNumericCellValue()) ,new RCell(v_RowNo ,v_ColumnNo));
                }
            }
        }
    }
    
    return v_Ret;
}
 
Example 18
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 19
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 20
Source File: MyExcelUtils.java    From spring-boot with Apache License 2.0 4 votes vote down vote up
/**
     * 根据 cell 格式,自动转换 cell 内容为 String
     *
     * @param cell
     * @param datePattern 日期格式  yyyy-MM-dd , yyyy-MM-dd HH:mm:ss  ...
     * @return
     */
    private static String getFormatCellValue(Cell cell, String datePattern) {

        //如果是日期格式,重新格式化
        if (cell.getCellTypeEnum() == CellType.NUMERIC && DateUtil.isCellDateFormatted(cell)) {

            return DateFormatUtils.format(cell.getDateCellValue(), datePattern);

        } else //默认格式化

            return new DataFormatter().formatCellValue(cell).trim();


        /**
         * DataFormatter().formatCellValue(cell) 的源码
         */
//        if (cell == null) {
//            return "";
//        }
//
//        int cellType = cell.getCellType();
//        if (cellType == Cell.CELL_TYPE_FORMULA) {
//            if (evaluator == null) {
//                return cell.getCellFormula();
//            }
//            cellType = evaluator.evaluateFormulaCell(cell);
//        }
//        switch (cellType) {
//            case Cell.CELL_TYPE_NUMERIC :
//
//                if (DateUtil.isCellDateFormatted(cell)) {
//                    return getFormattedDateString(cell);
//                }
//                return getFormattedNumberString(cell);
//
//            case Cell.CELL_TYPE_STRING :
//                return cell.getRichStringCellValue().getString();
//
//            case Cell.CELL_TYPE_BOOLEAN :
//                return String.valueOf(cell.getBooleanCellValue());
//            case Cell.CELL_TYPE_BLANK :
//                return "";
//            case Cell.CELL_TYPE_ERROR:
//                return FormulaError.forInt(cell.getErrorCellValue()).getString();
//        }
//        throw new RuntimeException("Unexpected celltype (" + cellType + ")");


    }