List of usage examples for org.apache.poi.hssf.usermodel HSSFCell getNumericCellValue
public double getNumericCellValue()
From source file:com.flexive.extractor.ExcelExtractor.java
License:Open Source License
private void processSheet(HSSFSheet sheet) { try {/* www .j a v a2s. co m*/ // Use the HFFS functions for the number of rows & columns int rowCount = sheet.getPhysicalNumberOfRows(); int colCount = sheet.getRow(0).getPhysicalNumberOfCells(); HSSFRow row; HSSFCell cell; String cellValue; for (int i = 0; i < rowCount; i++) { row = sheet.getRow(i); for (short j = 0; j < colCount; j++) { cell = row.getCell(j); if (cell != null) { try { switch (cell.getCellType()) { case HSSFCell.CELL_TYPE_BOOLEAN: cellValue = String.valueOf(cell.getBooleanCellValue()); break; case HSSFCell.CELL_TYPE_NUMERIC: cellValue = String.valueOf(cell.getNumericCellValue()); break; case HSSFCell.CELL_TYPE_FORMULA: // Doesnt make much sense to index a cell formula cellValue = ""; break; case HSSFCell.CELL_TYPE_ERROR: cellValue = String.valueOf(cell.getErrorCellValue()); break; case HSSFCell.CELL_TYPE_BLANK: cellValue = ""; break; default: cellValue = cell.getStringCellValue(); } } catch (Exception exc) { cellValue = ""; } writer.write(FxSharedUtils.getBytes(cellValue)); } } } } catch (Exception eN) { System.out.println("Error reading sheet:" + eN.toString()); } }
From source file:com.frameworkset.platform.cms.searchmanager.extractors.CmsExtractorMsExcel.java
License:Open Source License
/** * Extracts the text from the Excel table content.<p> * //from w w w .j av a 2 s . co m * @param in the document input stream * @return the extracted text * @throws IOException if something goes wring */ protected String extractTableContent(InputStream in) throws IOException { HSSFWorkbook excelWb = new HSSFWorkbook(in); StringBuffer result = new StringBuffer(4096); int numberOfSheets = excelWb.getNumberOfSheets(); for (int i = 0; i < numberOfSheets; i++) { HSSFSheet sheet = excelWb.getSheetAt(i); int numberOfRows = sheet.getPhysicalNumberOfRows(); if (numberOfRows > 0) { if (CmsStringUtil.isNotEmpty(excelWb.getSheetName(i))) { // append sheet name to content if (i > 0) { result.append("\n\n"); } result.append(excelWb.getSheetName(i).trim()); result.append(":\n\n"); } Iterator rowIt = sheet.rowIterator(); while (rowIt.hasNext()) { HSSFRow row = (HSSFRow) rowIt.next(); if (row != null) { boolean hasContent = false; Iterator it = row.cellIterator(); while (it.hasNext()) { HSSFCell cell = (HSSFCell) it.next(); String text = null; try { switch (cell.getCellType()) { case HSSFCell.CELL_TYPE_BLANK: case HSSFCell.CELL_TYPE_ERROR: // ignore all blank or error cells break; case HSSFCell.CELL_TYPE_NUMERIC: text = Double.toString(cell.getNumericCellValue()); break; case HSSFCell.CELL_TYPE_BOOLEAN: text = Boolean.toString(cell.getBooleanCellValue()); break; case HSSFCell.CELL_TYPE_STRING: default: text = cell.getStringCellValue(); break; } } catch (Exception e) { // ignore this cell } if (CmsStringUtil.isNotEmpty(text)) { result.append(text.trim()); result.append(' '); hasContent = true; } } if (hasContent) { // append a newline at the end of each row that has content result.append('\n'); } } } } } return result.toString(); }
From source file:com.frameworkset.platform.sanylog.util.POIExcelUtil.java
License:Open Source License
/** * ?Excel?MapList?Excel??Java./*w w w .ja va2s . c o m*/ * * @param file * @return * @throws IOException */ public static List<Map<String, Object>> parseHSSFMapList(MultipartFile file) throws IOException {// POIFSFileSystem poiFs = new POIFSFileSystem(file.getInputStream()); HSSFWorkbook wb = new HSSFWorkbook(poiFs); HSSFSheet sheet = wb.getSheetAt(0); int rowNum = sheet.getLastRowNum(); HSSFRow titleRow = sheet.getRow(0); int colNum = titleRow.getLastCellNum(); //?17 List<String> titleList = new ArrayList<String>(); for (int i = 0; i < colNum; i++) { String title = titleRow.getCell(i).getStringCellValue(); titleList.add(trimTitle(title)); } List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>(); for (int i = 1; i <= rowNum; i++) { HSSFRow row = sheet.getRow(i); Map<String, Object> map = new LinkedHashMap<String, Object>(); for (int j = 0; j < colNum; j++) { HSSFCell cell = row.getCell(j); if (cell != null) { switch (cell.getCellType()) { case HSSFCell.CELL_TYPE_NUMERIC: double d = cell.getNumericCellValue(); CellStyle style = cell.getCellStyle(); //? if (HSSFDateUtil.isCellDateFormatted(cell) || (style != null && (style.getDataFormat() == 57 || style.getDataFormat() == 58))) { map.put(titleList.get(j), HSSFDateUtil.getJavaDate(d)); } else { map.put(titleList.get(j), d); } break; default: cell.setCellType(HSSFCell.CELL_TYPE_STRING); map.put(titleList.get(j), row.getCell(j).getStringCellValue()); break; } } else { map.put(titleList.get(j), null); } } mapList.add(map); } return mapList; }
From source file:com.github.dougkelly88.FLIMPlateReaderGUI.SequencingClasses.Classes.FOVTableModel.java
public void loadFOVTableModelfromSpreadsheet() { ArrayList<FOV> load = new ArrayList(); HSSFSheet worksheet = HCAFLIMPluginFrame.wbLoad.getSheet("XYSequencing"); int RowSize = worksheet.getPhysicalNumberOfRows(); for (int RowNum = 0; RowNum < RowSize - 1; RowNum++) { HSSFRow row = worksheet.getRow(RowNum + 1); HSSFCell cell0 = row.getCell(0); HSSFCell cell1 = row.getCell(1); HSSFCell cell2 = row.getCell(2); HSSFCell cell3 = row.getCell(3); HSSFCell cell4 = row.getCell(4); FOV fov = new FOV(cell1.getNumericCellValue(), cell2.getNumericCellValue(), cell3.getNumericCellValue(), cell0.getStringCellValue(), pp_); fov.setGroup(cell4.getStringCellValue()); load.add(fov);/*from w w w .j ava 2 s . c o m*/ } data_ = load; fireTableDataChanged(); }
From source file:com.glaf.base.modules.todo.TodoXlsReader.java
License:Apache License
public List<Todo> readXls(java.io.InputStream inputStream) { List<Todo> todos = new java.util.ArrayList<Todo>(); HSSFWorkbook wb = null;/* w w w . j ava 2s. c o m*/ try { wb = new HSSFWorkbook(inputStream); } catch (Exception ex) { throw new RuntimeException(ex); } HSSFSheet sheet = wb.getSheetAt(0); HSSFRow row = sheet.getRow(1); Map<Integer, String> keyMap = new java.util.HashMap<Integer, String>(); Map<String, Object> dataMap = new java.util.HashMap<String, Object>(); int cells = row.getPhysicalNumberOfCells(); for (int colIndex = 0; colIndex < cells; colIndex++) { HSSFCell cell = row.getCell(colIndex); keyMap.put(colIndex, cell.getStringCellValue()); } Set<String> keys = new HashSet<String>(); for (int rowIndex = 2; rowIndex < sheet.getPhysicalNumberOfRows(); rowIndex++) { HSSFRow rowx = sheet.getRow(rowIndex); if (rowx == null) { continue; } // System.out.println(); dataMap.clear(); for (int colIndex = 0; colIndex < cells; colIndex++) { String fieldName = keyMap.get(colIndex); HSSFCell cell = rowx.getCell(colIndex); if (cell == null) { continue; } Object cellValue = null; switch (cell.getCellType()) { case HSSFCell.CELL_TYPE_FORMULA: break; case HSSFCell.CELL_TYPE_BOOLEAN: cellValue = cell.getBooleanCellValue(); break; case HSSFCell.CELL_TYPE_NUMERIC: cellValue = cell.getNumericCellValue(); break; case HSSFCell.CELL_TYPE_STRING: if (StringUtils.isNotEmpty(cell.getRichStringCellValue().getString())) { cellValue = cell.getRichStringCellValue().getString(); } break; default: if (StringUtils.isNotEmpty(cell.getStringCellValue())) { cellValue = cell.getStringCellValue(); } break; } if (cellValue != null) { dataMap.put(fieldName, cellValue); if ("id".equals(fieldName)) { cellValue = cellValue.toString().substring(0, cellValue.toString().indexOf(".")); dataMap.put(fieldName, cellValue); } } } if (dataMap.get("code") != null) { String id = ParamUtils.getString(dataMap, "id"); if (!keys.contains(ParamUtils.getString(dataMap, "code"))) { if (id != null && StringUtils.isNotEmpty(id)) { Todo model = new Todo(); Tools.populate(model, dataMap); if (ParamUtils.getInt(dataMap, "limitDay") > 0) { model.setLimitDay(ParamUtils.getInt(dataMap, "limitDay")); } todos.add(model); keys.add(model.getCode()); } } } } return todos; }
From source file:com.glaf.core.todo.util.TodoXlsReader.java
License:Apache License
public List<Todo> readXls(java.io.InputStream inputStream) { List<Todo> todos = new java.util.ArrayList<Todo>(); HSSFWorkbook wb = null;/* ww w . j av a 2 s .c om*/ try { wb = new HSSFWorkbook(inputStream); HSSFSheet sheet = wb.getSheetAt(0); HSSFRow row = sheet.getRow(1); Map<Integer, String> keyMap = new java.util.HashMap<Integer, String>(); Map<String, Object> dataMap = new java.util.HashMap<String, Object>(); int cells = row.getPhysicalNumberOfCells(); for (int colIndex = 0; colIndex < cells; colIndex++) { HSSFCell cell = row.getCell(colIndex); keyMap.put(colIndex, cell.getStringCellValue()); } int sortNo = 1; Set<String> keys = new HashSet<String>(); for (int rowIndex = 2; rowIndex < sheet.getPhysicalNumberOfRows(); rowIndex++) { HSSFRow rowx = sheet.getRow(rowIndex); if (rowx == null) { continue; } // System.out.println(); dataMap.clear(); for (int colIndex = 0; colIndex < cells; colIndex++) { String fieldName = keyMap.get(colIndex); HSSFCell cell = rowx.getCell(colIndex); if (cell == null) { continue; } Object cellValue = null; switch (cell.getCellType()) { case HSSFCell.CELL_TYPE_FORMULA: break; case HSSFCell.CELL_TYPE_BOOLEAN: cellValue = cell.getBooleanCellValue(); break; case HSSFCell.CELL_TYPE_NUMERIC: cellValue = cell.getNumericCellValue(); break; case HSSFCell.CELL_TYPE_STRING: if (StringUtils.isNotEmpty(cell.getRichStringCellValue().getString())) { cellValue = cell.getRichStringCellValue().getString(); } break; default: if (StringUtils.isNotEmpty(cell.getStringCellValue())) { cellValue = cell.getStringCellValue(); } break; } if (cellValue != null) { dataMap.put(fieldName, cellValue); // System.out.print("\t" + fieldName + "=" + cellValue); } } if (dataMap.get("code") != null) { String id = ParamUtils.getString(dataMap, "id"); Todo model = new Todo(); dataMap.remove("id"); Tools.populate(model, dataMap); if (!keys.contains(model.getCode())) { model.setSortNo(sortNo++); if (id != null) { model.setId(Long.parseLong(id)); } if (ParamUtils.getDouble(dataMap, "limitDay") > 0) { model.setLimitDay(ParamUtils.getInt(dataMap, "limitDay")); } todos.add(model); keys.add(model.getCode()); } } } } catch (Exception ex) { throw new RuntimeException(ex); } finally { if (wb != null) { try { wb.close(); wb = null; } catch (IOException e) { } } } return todos; }
From source file:com.googlecode.bdoc.testsupport.excel.ExcelExampleTable.java
License:Open Source License
/** * Gets cell values from row//ww w .ja va2s . c o m * * @param relativRowIndex * to the description and cell headers * @return cell values for the given row */ public List<Object> getRow(int relativRowIndex) { List<Object> result = new ArrayList<Object>(); HSSFRow row = sheet.getRow(startingRowIndex + 2 + relativRowIndex); for (int cellnum = 0; cellnum < row.getLastCellNum(); cellnum++) { HSSFCell cell = row.getCell(cellnum); try { int cellType = cell.getCellType(); switch (cellType) { case HSSFCell.CELL_TYPE_NUMERIC: { result.add(cell.getNumericCellValue()); continue; } case HSSFCell.CELL_TYPE_FORMULA: { result.add(cell.getNumericCellValue()); continue; } case HSSFCell.CELL_TYPE_STRING: { result.add(cell.getRichStringCellValue().getString()); continue; } default: { throw new IllegalStateException("can't handle value"); } } } catch (Exception e) { throw new ExcelTableCellReadException(row.getRowNum() + 1, cellnum, cell, e); } } return result; }
From source file:com.ibm.asset.trails.service.impl.CauseCodeServiceImpl.java
private void saveCauseCode(HSSFWorkbook wb, String remoteUser, List<State> steps) { HSSFSheet sheet = wb.getSheetAt(0);//from w w w. ja v a 2 s. co m Iterator<Row> rowIter = sheet.rowIterator(); State state = State.findStateByLable(steps, STEP3_LABEL); if (state == null) { state = new State(); state.setDescription("Persist changes"); state.setLabel(STEP3_LABEL); state.setStatus(EStatus.IN_PROGRESS); steps.add(state); } int rowCounter = -1; int totalRows = sheet.getLastRowNum(); while (rowIter.hasNext()) { HSSFRow row = (HSSFRow) rowIter.next(); rowCounter++; int progress = (int) ((float) rowCounter / totalRows * 100); state.setProgress(progress); if (progress == 100) { state.setStatus(EStatus.FINISHED); } if (rowCounter <= ROW_TABLE_HEAD) { continue; } HSSFCell causeCodeIdCell = row.getCell(colIndexes.getColInternalId()); long causeCodeId = -1; if (causeCodeIdCell.getCellType() == HSSFCell.CELL_TYPE_STRING) { causeCodeId = Long.valueOf(causeCodeIdCell.getStringCellValue()); } else if (causeCodeIdCell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) { causeCodeId = Math.round(causeCodeIdCell.getNumericCellValue()); } CauseCode causeCode = (CauseCode) getEntityManager().createNamedQuery("getCauseCodeById") .setParameter("id", causeCodeId).getSingleResult(); String causeCodeName = causeCode.getAlertCause().getName(); HSSFCell causeCodeCell = row.getCell(colIndexes.getColCauseCode()); String colCauseCode = null; if (causeCodeCell != null) { colCauseCode = causeCodeCell.getStringCellValue().trim(); } Date targetDate = causeCode.getTargetDate(); HSSFCell targetDateCell = row.getCell(colIndexes.getColTargetDate()); Date colTargetDate = null; if (targetDateCell != null) { if (targetDateCell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC && HSSFDateUtil.isCellDateFormatted(targetDateCell)) { colTargetDate = targetDateCell.getDateCellValue(); } else if (targetDateCell.getCellType() == HSSFCell.CELL_TYPE_STRING) { colTargetDate = convertTextToDate(targetDateCell);//Convert Date Text to Date Object } } String owner = causeCode.getOwner(); HSSFCell ownerCell = row.getCell(colIndexes.getColOwner()); String colOwner = null; if (ownerCell != null) { colOwner = ownerCell.getStringCellValue().trim(); } //Assignee Comments Function Start if (colIndexes.getColAssigneeComments() != -1) { HSSFCell assigneeCommentsCell = row.getCell(colIndexes.getColAssigneeComments()); String assigneeComments = ""; if (assigneeCommentsCell != null && assigneeCommentsCell.getCellType() == HSSFCell.CELL_TYPE_STRING) { assigneeComments = assigneeCommentsCell.getStringCellValue(); } if (assigneeComments != null && !"".equals(assigneeComments.trim())) { updateAssigneeComments(causeCode.getAlertId(), assigneeComments.trim(), colIndexes.getReportName().trim(), remoteUser); } } //Assignee Comments Function End boolean changed = false; if (!strCompare(causeCodeName, colCauseCode) || !dateCompare(targetDate, colTargetDate) || !strCompare(owner, colOwner)) { changed = true; } if (!changed) { continue; } CauseCodeHistory history = new CauseCodeHistory(); history.setCauseCode(causeCode); history.setAlertType(causeCode.getAlertType()); history.setAlertId(causeCode.getAlertId()); history.setAlertCause(causeCode.getAlertCause()); history.setTargetDate(causeCode.getTargetDate()); history.setOwner(causeCode.getOwner()); history.setRecordTime(causeCode.getRecordTime()); history.setRemoteUser(causeCode.getRemoteUser()); if (!strCompare(causeCodeName, colCauseCode)) { try { AlertCause alertCause = null; if ("UNDEFINED".equals(colCauseCode.trim().toUpperCase())) { alertCause = (AlertCause) getEntityManager() .createNamedQuery("findAlertCauseByNameWithoutShowInGui") .setParameter("name", colCauseCode.trim().toUpperCase()).getSingleResult(); } else { alertCause = (AlertCause) getEntityManager().createNamedQuery("findAlertCauseByName") .setParameter("name", colCauseCode.trim().toUpperCase()).getSingleResult(); } if (alertCause != null) { causeCode.setAlertCause(alertCause); } } catch (Exception e) { log.error(e.getMessage(), e); } } if (!dateCompare(targetDate, colTargetDate)) { causeCode.setTargetDate(colTargetDate); } if (!strCompare(owner, colOwner)) { causeCode.setOwner(colOwner); } causeCode.setRemoteUser(remoteUser); causeCode.setRecordTime(new Date()); try { getEntityManager().persist(history); getEntityManager().persist(causeCode); getEntityManager().flush(); } catch (Exception e) { log.error(e.getMessage(), e); } } }
From source file:com.ibm.asset.trails.service.impl.CauseCodeServiceImpl.java
private Long parseCauseCodeIdCell(HSSFCell cell) { long causeCodeId; if (cell != null && cell.getCellType() == HSSFCell.CELL_TYPE_STRING) { String content = cell.getStringCellValue(); Pattern pattern = Pattern.compile("[0-9]*"); if (!pattern.matcher(content).matches()) { return null; }//from w w w . j a va2 s. c o m causeCodeId = Long.valueOf(content); } else if (cell != null && cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) { causeCodeId = Math.round(cell.getNumericCellValue()); } else { return null; } return causeCodeId; }
From source file:com.ibm.ioes.actions.NewOrderAction.java
/** * @param templateStream //w ww .j a v a2 s. co m * @method saveUploadedFileInfo * @purpose save uploaded file data in staging table in database * @param FormFile, * filepath, userName * @param excel_uploadPath, * uploadedFilePath * @return * @throws NpdException */ public int saveUploadedFileInfo(FormFile uploadedFile, int productID, String templateFilePath) throws IOESException { // AppConstants.IOES_LOGGER.info("saveUploadedFileInfo() started"); int sheetCol, sheetRow; ArrayList<Object[][]> excelDataList = new ArrayList<Object[][]>(); int thisSaveCode = 0; int saveStatusCode = 0; try { String fileName = null; if (uploadedFile != null) { fileName = uploadedFile.getFileName(); } if (fileName != null) { HSSFWorkbook workbook = null; HSSFSheet sheet = null; HSSFRow rowInSheet = null; HSSFCell cellInSheet = null; workbook = new HSSFWorkbook(uploadedFile.getInputStream()); for (int count = 0; count < workbook.getNumberOfSheets() - 1; count++) { sheet = workbook.getSheetAt(count); sheetRow = sheet.getLastRowNum(); sheetCol = sheet.getRow(0).getLastCellNum(); Object excelData[][] = new Object[sheetRow][sheetCol]; for (int r = 1; r <= sheetRow; r++) { rowInSheet = sheet.getRow(r); int columIndex = 0; for (int c = 1; c < sheetCol + 1; c++) { if (rowInSheet != null) { cellInSheet = rowInSheet.getCell(c - 1); if (cellInSheet != null) { if (cellInSheet.getCellType() == 0) { excelData[r - 1][columIndex++] = Utility.convertWithOutE_WithOutDotZero( String.valueOf(cellInSheet.getNumericCellValue())); /*NumberFormat formatter = new DecimalFormat("0"); excelData[r - 1][columIndex++] = formatter .format(cellInSheet.getNumericCellValue());*/ } else { excelData[r - 1][columIndex++] = cellInSheet.toString().trim(); } } else { excelData[r - 1][columIndex++] = ""; } } else { excelData[r - 1][columIndex++] = ""; } } } excelDataList.add(excelData); } } //if (checkCode == 1) { NewOrderModel model = new NewOrderModel(); saveStatusCode = model.saveUploadedFileToTemporaryTable(excelDataList, productID, fileName); if (saveStatusCode > 0) { thisSaveCode = 1; } else { thisSaveCode = 0; } /*} else { thisSaveCode= 0; }*/ // AppConstants.IOES_LOGGER.info("Completed.."); return thisSaveCode; } catch (Exception ed) { ed.printStackTrace(); AppConstants.IOES_LOGGER.error("Error while getting saveUploadedFileInfo " + ed.getMessage()); throw new IOESException(ed); } finally { AppConstants.IOES_LOGGER.info("saveUploadedFileInfo() completed"); } }