Java Code Examples for org.apache.poi.ss.usermodel.CellType#STRING
The following examples show how to use
org.apache.poi.ss.usermodel.CellType#STRING .
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: StreamingCell.java From excel-streaming-reader with Apache License 2.0 | 7 votes |
/** * 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 2
Source File: StreamingCell.java From excel-streaming-reader with Apache License 2.0 | 6 votes |
/** * 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 3
Source File: HSSFCell.java From lams with GNU General Public License v2.0 | 6 votes |
/** * used internally -- given a cell value record, figure out its type */ private static CellType determineType(CellValueRecordInterface cval) { if (cval instanceof FormulaRecordAggregate) { return CellType.FORMULA; } // all others are plain BIFF records Record record = ( Record ) cval; switch (record.getSid()) { case NumberRecord.sid : return CellType.NUMERIC; case BlankRecord.sid : return CellType.BLANK; case LabelSSTRecord.sid : return CellType.STRING; case BoolErrRecord.sid : BoolErrRecord boolErrRecord = ( BoolErrRecord ) record; return boolErrRecord.isBoolean() ? CellType.BOOLEAN : CellType.ERROR; } throw new RuntimeException("Bad cell value rec (" + cval.getClass().getName() + ")"); }
Example 4
Source File: FlatFileExtractor.java From Open-Lowcode with Eclipse Public License 2.0 | 5 votes |
/** * 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 5
Source File: AbstractSheet.java From tools with Apache License 2.0 | 5 votes |
/** * @param cell * @return */ @SuppressWarnings("deprecation") private int getNumWrappedLines(Cell cell) { if (cell.getCellTypeEnum() == CellType.STRING) { String val = cell.getStringCellValue(); if (val == null || val.isEmpty()) { return 1; } CellStyle style = cell.getCellStyle(); if (style == null || !style.getWrapText()) { return 1; } Font font = sheet.getWorkbook().getFontAt(style.getFontIndex()); AttributedString astr = new AttributedString(val); java.awt.Font awtFont = new java.awt.Font(font.getFontName(), 0, font.getFontHeightInPoints()); float cellWidth = sheet.getColumnWidth(cell.getColumnIndex())/ 256F * 5.5F; astr.addAttribute(TextAttribute.FONT, awtFont); FontRenderContext context = new FontRenderContext(null, true, true); java.awt.font.LineBreakMeasurer measurer = new java.awt.font.LineBreakMeasurer(astr.getIterator(), context); int pos = 0; int numLines = 0; while (measurer.getPosition() < val.length()) { pos = measurer.nextOffset(cellWidth); numLines++; measurer.setPosition(pos); } return numLines; } else { // Not a string type return 1; } }
Example 6
Source File: AdultObesityImporter.java From TomboloDigitalConnector with MIT License | 5 votes |
@Override protected void importDatasource(Datasource datasource, List<String> geographyScope, List<String> temporalScope, List<String> datasourceLocation) throws Exception { // Choose the apppropriate workbook sheet Workbook workbook = excelUtils.getWorkbook( downloadUtils.fetchInputStream(new URL(DATASOURCE), getProvider().getLabel(), DATASOURCE_SUFFIX)); Sheet sheet = workbook.getSheet("Active People Survey"); String year = "2013"; List<TimedValueExtractor> timedValueExtractors = new ArrayList<>(); RowCellExtractor subjectExtractor = new RowCellExtractor(0, CellType.STRING); ConstantExtractor timestampExtractor = new ConstantExtractor(year); SubjectType subjectType = SubjectTypeUtils.getOrCreate(AbstractONSImporter.PROVIDER, OaImporter.OaType.localAuthority.name(), OaImporter.OaType.localAuthority.datasourceSpec.getDescription()); for (AttributeLabel attributeLabel : AttributeLabel.values()){ ConstantExtractor attributeExtractor = new ConstantExtractor(attributeLabel.name()); RowCellExtractor valueExtractor = new RowCellExtractor(getAttributeColumnId(attributeLabel), CellType.NUMERIC); timedValueExtractors.add(new TimedValueExtractor( getProvider(), subjectType, subjectExtractor, attributeExtractor, timestampExtractor, valueExtractor)); } excelUtils.extractAndSaveTimedValues(sheet, this, timedValueExtractors); }
Example 7
Source File: OneClickImporterServiceImpl.java From molgenis with GNU Lesser General Public License v3.0 | 5 votes |
/** * Specific columntypes are permitted in the import. The supported columntypes are specified in * the method. * * @param sheet worksheet * @param cell cell on worksheet * @return Column */ private Column createColumnFromCell(Sheet sheet, Cell cell) { if (cell.getCellTypeEnum() == CellType.STRING) { return Column.create( cell.getStringCellValue(), cell.getColumnIndex(), getColumnDataFromSheet(sheet, cell.getColumnIndex())); } else { throw new MolgenisDataException( String.format( "Celltype [%s] is not supported for columnheaders", cell.getCellTypeEnum())); } }
Example 8
Source File: ForkedEvaluationCell.java From lams with GNU General Public License v2.0 | 5 votes |
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 9
Source File: XLSFormatter.java From yarg with Apache License 2.0 | 5 votes |
/** * 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 10
Source File: SpreadsheetTab.java From taro with MIT License | 5 votes |
public void autoSizeRow(int row) { float tallestCell = -1; for (int col = 0; col <= highestModifiedCol; col++) { SpreadsheetCell cell = getOrCreateCell(row, col); int fontSize = cell.getFontSizeInPoints(); XSSFCell poiCell = cell.getPoiCell(); if (poiCell.getCellType() == CellType.STRING) { String value = poiCell.getStringCellValue(); int numLines = 1; for (int i = 0; i < value.length(); i++) { if (value.charAt(i) == '\n') numLines++; } float cellHeight = computeRowHeightInPoints(fontSize, numLines); if (cellHeight > tallestCell) { tallestCell = cellHeight; } } } float defaultRowHeightInPoints = sheet.getDefaultRowHeightInPoints(); float rowHeight = tallestCell; if (rowHeight < defaultRowHeightInPoints+1) { rowHeight = -1; // resets to the default } sheet.getRow(row).setHeightInPoints(rowHeight); }
Example 11
Source File: HSSFCell.java From lams with GNU General Public License v2.0 | 4 votes |
/** * Set a string value for the cell. * * @param value value to set the cell to. For formulas we'll set the formula * string, for String cells we'll set its value. For other types we will * change the cell to a string cell and set its value. * If value is <code>null</code> then we will change the cell to a Blank cell. */ public void setCellValue(RichTextString value) { int row=_record.getRow(); short col=_record.getColumn(); short styleIndex=_record.getXFIndex(); if (value == null) { notifyFormulaChanging(); setCellType(CellType.BLANK, false, row, col, styleIndex); return; } if(value.length() > SpreadsheetVersion.EXCEL97.getMaxTextLength()){ throw new IllegalArgumentException("The maximum length of cell contents (text) is 32,767 characters"); } if (_cellType == CellType.FORMULA) { // Set the 'pre-evaluated result' for the formula // note - formulas do not preserve text formatting. FormulaRecordAggregate fr = (FormulaRecordAggregate) _record; fr.setCachedStringResult(value.getString()); // Update our local cache to the un-formatted version _stringValue = new HSSFRichTextString(value.getString()); // All done return; } // If we get here, we're not dealing with a formula, // so handle things as a normal rich text cell if (_cellType != CellType.STRING) { setCellType(CellType.STRING, false, row, col, styleIndex); } int index = 0; HSSFRichTextString hvalue = (HSSFRichTextString) value; UnicodeString str = hvalue.getUnicodeString(); index = _book.getWorkbook().addSSTString(str); (( LabelSSTRecord ) _record).setSSTIndex(index); _stringValue = hvalue; _stringValue.setWorkbookReferences(_book.getWorkbook(), (( LabelSSTRecord ) _record)); _stringValue.setUnicodeString(_book.getWorkbook().getSSTString(index)); }
Example 12
Source File: ExcelHelp.java From hy.common.report with Apache License 2.0 | 4 votes |
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 13
Source File: JavaToExcel.java From hy.common.report with Apache License 2.0 | 4 votes |
/** * 复制单位格(空白行的复制,即只复制格式和固定文字,不填充数据) * * @author ZhengWei(HY) * @createDate 2017-07-03 * @version v1.0 * * @param i_RTemplate 模板对象 * @param i_TemplateCell 模板中的单元格对象 * @param i_DataWorkbook 数据工作薄 * @param i_DataCell 数据中的单元格对象 * @param io_RSystemValue 系统变量信息 * @param i_Datas 本行对应的数据 * @param io_RValue 小计循环的迭代器 * @return */ public final static void copyCellByBlankSpace(RTemplate i_RTemplate ,Cell i_TemplateCell ,RWorkbook i_DataWorkbook ,Cell i_DataCell ,RSystemValue io_RSystemValue) { // 复制样式 i_DataCell.setCellStyle(i_DataWorkbook.getCellStyle(i_RTemplate ,i_TemplateCell.getCellStyle().getIndex())); // 复制评论 copyComment(i_RTemplate ,i_TemplateCell ,i_DataWorkbook ,i_DataCell); // 复制数据类型 CellType v_CellType = i_TemplateCell.getCellTypeEnum(); // i_DataCell.setCellType(v_CellType); 不能在此统一设置,原因是:下面代码对类型是有浮动的 if ( v_CellType == CellType.NUMERIC ) { i_DataCell.setCellType(v_CellType); if ( HSSFDateUtil.isCellDateFormatted(i_TemplateCell) ) { i_DataCell.setCellValue(i_TemplateCell.getDateCellValue()); } else { i_DataCell.setCellValue(i_TemplateCell.getNumericCellValue()); } } else if ( v_CellType == CellType.STRING ) { RichTextString v_TemplateRichText = i_TemplateCell.getRichStringCellValue(); String v_ValueName = v_TemplateRichText.toString(); if ( i_RTemplate.isExists(v_ValueName) ) { i_DataCell.setCellType(v_CellType); i_DataCell.setCellValue(""); } else { i_DataCell.setCellType(v_CellType); copyRichTextStyle(i_RTemplate ,v_TemplateRichText ,i_DataWorkbook ,i_DataCell); } } else if ( v_CellType == CellType.BOOLEAN ) { i_DataCell.setCellType(v_CellType); i_DataCell.setCellValue(i_TemplateCell.getBooleanCellValue()); } else if ( v_CellType == CellType.FORMULA) { i_DataCell.setCellType(v_CellType); i_DataCell.setCellFormula(ExcelFormula.calcFormulaOffset(i_TemplateCell ,i_DataCell)); } else { // Nothing. i_DataCell.setCellType(v_CellType); } }
Example 14
Source File: ImportDataUtils.java From opencps-v2 with GNU Affero General Public License v3.0 | 4 votes |
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: WalkingCyclingBoroughImporter.java From TomboloDigitalConnector with MIT License | 4 votes |
@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.localAuthority.name(), OaImporter.OaType.localAuthority.datasourceSpec.getDescription()); Workbook workbook = excelUtils.getWorkbook( downloadUtils.fetchInputStream(new URL(DATAFILE), getProvider().getLabel(), DATAFILE_SUFFIX)); RowCellExtractor subjectLabelExtractor = new RowCellExtractor(0, CellType.STRING); // Extract walking ConstantExtractor walk5xWeekAttributeLabelExtractor = new ConstantExtractor(AttributeId.walk5xWeek.name()); List<TimedValueExtractor> walk5xWeekExtractors = new ArrayList<>(); walk5xWeekExtractors.add(new TimedValueExtractor( getProvider(), subjectType, subjectLabelExtractor, walk5xWeekAttributeLabelExtractor, new ConstantExtractor("2011-12-31T23:59:59"), new RowCellExtractor(7,CellType.NUMERIC) )); walk5xWeekExtractors.add(new TimedValueExtractor( getProvider(), subjectType, subjectLabelExtractor, walk5xWeekAttributeLabelExtractor, new ConstantExtractor("2012-12-31T23:59:59"), new RowCellExtractor(18, CellType.NUMERIC) )); walk5xWeekExtractors.add(new TimedValueExtractor( getProvider(), subjectType, subjectLabelExtractor, walk5xWeekAttributeLabelExtractor, new ConstantExtractor("2013-12-31T23:59:59"), new RowCellExtractor(29, CellType.NUMERIC) )); walk5xWeekExtractors.add(new TimedValueExtractor( getProvider(), subjectType, subjectLabelExtractor, walk5xWeekAttributeLabelExtractor, new ConstantExtractor("2014-12-31T23:59:59"), new RowCellExtractor(40, CellType.NUMERIC) )); Sheet walkSheet = workbook.getSheetAt(1); excelUtils.extractAndSaveTimedValues(walkSheet, this, walk5xWeekExtractors); // Extract cycling ConstantExtractor cycle1xWeekAttributeLabelExtractor = new ConstantExtractor(AttributeId.cycle1xWeek.name()); List<TimedValueExtractor> cycle1xWeekExtractors = new ArrayList<>(); cycle1xWeekExtractors.add(new TimedValueExtractor( getProvider(), subjectType, subjectLabelExtractor, cycle1xWeekAttributeLabelExtractor, new ConstantExtractor("2011-12-31T23:59:59"), new RowCellExtractor(5, CellType.NUMERIC) )); cycle1xWeekExtractors.add(new TimedValueExtractor( getProvider(), subjectType, subjectLabelExtractor, cycle1xWeekAttributeLabelExtractor, new ConstantExtractor("2012-12-31T23:59:59"), new RowCellExtractor(16, CellType.NUMERIC) )); cycle1xWeekExtractors.add(new TimedValueExtractor( getProvider(), subjectType, subjectLabelExtractor, cycle1xWeekAttributeLabelExtractor, new ConstantExtractor("2013-12-31T23:59:59"), new RowCellExtractor(27, CellType.NUMERIC) )); cycle1xWeekExtractors.add(new TimedValueExtractor( getProvider(), subjectType, subjectLabelExtractor, cycle1xWeekAttributeLabelExtractor, new ConstantExtractor("2014-12-31T23:59:59"), new RowCellExtractor(38, CellType.NUMERIC) )); Sheet cycleSheet = workbook.getSheetAt(2); excelUtils.extractAndSaveTimedValues(cycleSheet, this, cycle1xWeekExtractors); }
Example 16
Source File: ExcelUtil.java From LuckyFrameWeb with GNU Affero General Public License v3.0 | 4 votes |
/** * 获取单元格值 * * @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 17
Source File: SpreadsheetReader.java From taro with MIT License | 4 votes |
public boolean isString(int col, int row) { return getCellType(col, row) == CellType.STRING; }
Example 18
Source File: ExcelUtil.java From RuoYi-Vue with MIT License | 4 votes |
/** * 获取单元格值 * * @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: XlsSchemaParser.java From data-prep with Apache License 2.0 | 4 votes |
/** * We store (cell types per row) per column. * * @param sheet key is the column number, value is a Map with key row number and value Type * @return A Map<colId, Map<rowId, type>> */ private SortedMap<Integer, SortedMap<Integer, String>> collectSheetTypeMatrix(Sheet sheet, FormulaEvaluator formulaEvaluator) { int firstRowNum = sheet.getFirstRowNum(); int lastRowNum = sheet.getLastRowNum(); LOGGER.debug("firstRowNum: {}, lastRowNum: {}", firstRowNum, lastRowNum); SortedMap<Integer, SortedMap<Integer, String>> cellsTypeMatrix = new TreeMap<>(); // we start analysing rows for (int rowCounter = firstRowNum; rowCounter <= lastRowNum; rowCounter++) { int cellCounter = 0; Row row = sheet.getRow(rowCounter); if (row == null) { continue; } Iterator<Cell> cellIterator = row.cellIterator(); String currentType; while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); CellType xlsType = CellType.STRING; try { xlsType = cell.getCellType() == CellType.FORMULA ? // formulaEvaluator.evaluate(cell).getCellType() : cell.getCellType(); } catch (Exception e) { // ignore formula error evaluation get as a String with the formula } switch (xlsType) { case BOOLEAN: currentType = BOOLEAN.getName(); break; case NUMERIC: currentType = getTypeFromNumericCell(cell); break; case BLANK: currentType = BLANK; break; case FORMULA: case STRING: currentType = STRING.getName(); break; case ERROR: // we cannot really do anything with an error default: currentType = ANY.getName(); } SortedMap<Integer, String> cellInfo = cellsTypeMatrix.get(cellCounter); if (cellInfo == null) { cellInfo = new TreeMap<>(); } cellInfo.put(rowCounter, currentType); cellsTypeMatrix.put(cellCounter, cellInfo); cellCounter++; } } LOGGER.trace("cellsTypeMatrix: {}", cellsTypeMatrix); return cellsTypeMatrix; }
Example 20
Source File: StreamingCell.java From excel-streaming-reader with Apache License 2.0 | 3 votes |
/** * Get the value of the cell as a date. For strings we throw an exception. For * blank cells we return a null. * * @return the value of the cell as a date * @throws IllegalStateException if the cell type returned by {@link #getCellType()} is CELL_TYPE_STRING * @throws NumberFormatException if the cell value isn't a parsable <code>double</code>. */ @Override public Date getDateCellValue() { if(getCellType() == CellType.STRING){ throw new IllegalStateException("Cell type cannot be CELL_TYPE_STRING"); } return rawContents == null ? null : HSSFDateUtil.getJavaDate(getNumericCellValue(), use1904Dates); }