List of usage examples for org.apache.poi.ss.usermodel Cell getNumericCellValue
double getNumericCellValue();
From source file:com.krawler.esp.servlets.XLSDataExtractor.java
License:Open Source License
public JSONObject parseXLS1(String filename, int sheetNo) throws FileNotFoundException, IOException, JSONException { JSONObject jobj = new JSONObject(); POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(filename)); HSSFWorkbook wb = new HSSFWorkbook(fs); HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(wb); HSSFSheet sheet = wb.getSheetAt(sheetNo); ArrayList<String> arr = new ArrayList<String>(); int startRow = 0; int maxRow = sheet.getLastRowNum(); int maxCol = 0; JSONArray jArr = new JSONArray(); try {/*from w ww . ja v a 2 s .com*/ for (int i = 0; i <= sheet.getLastRowNum(); i++) { Row row = sheet.getRow(i); JSONObject obj = new JSONObject(); JSONObject jtemp1 = new JSONObject(); if (row == null) { jArr.put(obj); continue; } if (maxCol < row.getLastCellNum()) maxCol = row.getLastCellNum(); for (int j = 0; j < row.getLastCellNum(); j++) { Cell cell = row.getCell(j); String val = null; if (cell == null) { arr.add(val); continue; } ; String colHeader = new CellReference(i, j).getCellRefParts()[2]; switch (cell.getCellType()) { case Cell.CELL_TYPE_NUMERIC: val = Double.toString(cell.getNumericCellValue()); if (HSSFDateUtil.isCellDateFormatted(cell)) { java.util.Date df = HSSFDateUtil.getJavaDate(Double.parseDouble(val)); String df_full = "yyyy-MM-dd"; DateFormat sdf = new SimpleDateFormat(df_full); val = sdf.format(df); } break; case Cell.CELL_TYPE_STRING: val = cell.getRichStringCellValue().getString(); break; } if (i == 0) { // List of Headers (Consider first row as Headers) jtemp1 = new JSONObject(); jtemp1.put("header", val); jtemp1.put("index", j); jobj.append("Header", jtemp1); obj.put(colHeader, val); arr.add(val); } else { if (arr.get(j) != null) obj.put(arr.get(j), val); } } jArr.put(obj); } } catch (Exception ex) { Logger.getLogger(XLSDataExtractor.class.getName()).log(Level.SEVERE, null, ex); } jobj.put("startrow", startRow); jobj.put("maxrow", maxRow); jobj.put("maxcol", maxCol); jobj.put("index", sheetNo); jobj.put("data", jArr); jobj.put("filename", filename); jobj.put("msg", "Image has been successfully uploaded"); jobj.put("lsuccess", true); jobj.put("valid", true); return jobj; }
From source file:com.ksa.myanmarlottery.service.parser.ExcelFileParser.java
@Override public List<Result> getResult(InputStream in) throws FileNotFoundException, IOException, ParseException { List<Prize> prizes = null; List<Result> resultList = new ArrayList<>(); SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy"); // 01-May-2017 try {//from w w w.j a va 2 s.com Workbook workbook = new XSSFWorkbook(in); Sheet datatypeSheet = workbook.getSheetAt(0); Iterator<Row> iterator = datatypeSheet.iterator(); while (iterator.hasNext()) { Row currentRow = iterator.next(); Cell cell0 = currentRow.getCell(0); // get first cell. if (cell0.getCellTypeEnum() == CellType.NUMERIC) { int numberic = (int) cell0.getNumericCellValue(); log.info("Numberic - " + numberic); // check lottery type if (ConstantUtil.OLD_LOTTERY_TYPE == numberic || ConstantUtil.NEW_LOTTERY_TYPE == numberic) { // for lottery type result Result result = new Result(); result.setType(numberic); result.setNumberOfTimes((int) currentRow.getCell(1).getNumericCellValue()); // result.setResultFor(format.parse(currentRow.getCell(2).toString())); result.setResultFor(currentRow.getCell(2).getDateCellValue()); result.setDataProvider(currentRow.getCell(3).getStringCellValue()); result.setCompanyName(currentRow.getCell(4).getStringCellValue()); prizes = new ArrayList<>(); result.setPrizes(prizes); resultList.add(result); } } else if (cell0.getCellTypeEnum() == CellType.STRING) { // result data String character = cell0.getStringCellValue(); log.info("character - " + character); // check validation for character. String value = charMap.get(character); if (value == null) { throw new ParseException( "Character is Not valid at Row: " + currentRow.getRowNum() + " > column:" + 0, 400); } Cell cell1 = currentRow.getCell(1); if (cell1.getCellTypeEnum() != CellType.NUMERIC) { throw new ParseException( "Should be Number at Row: " + currentRow.getRowNum() + " > column:" + 1, 400); } log.info("Cell Type " + cell1.getCellTypeEnum()); int code = (int) cell1.getNumericCellValue(); log.info("code - " + code + " Row:" + currentRow.getRowNum() + " > column:" + 1); String prizeTitle = currentRow.getCell(2).getStringCellValue(); log.info("prizeTitle - " + prizeTitle); String prizeDesc = currentRow.getCell(4).getStringCellValue(); log.info("prizeDesc - " + prizeDesc); prizes.add(new Prize(character, code, prizeTitle, prizeDesc)); } } log.info("resultList size: " + resultList.size()); for (Result r : resultList) { log.info("prizeList size: " + r.getPrizes().size()); } } catch (FileNotFoundException e) { e.printStackTrace(); throw e; } catch (IOException e) { e.printStackTrace(); throw e; } return resultList; }
From source file:com.kybelksties.excel.ExcelSheetTableModel.java
License:Open Source License
/** * Get the value contained in the cell./* w w w.jav a2 s . c o m*/ * * @param cell the examined cell * @return the value as Boolean, Numeric, String, Blank, Error or Formula */ public static Object getCellValue(Cell cell) { return cell == null ? "" : cell.getCellType() == Cell.CELL_TYPE_BOOLEAN ? cell.getBooleanCellValue() : cell.getCellType() == Cell.CELL_TYPE_NUMERIC ? (DateUtil.isCellDateFormatted(cell) ? cell.getDateCellValue() : cell.getNumericCellValue()) : cell.getCellType() == Cell.CELL_TYPE_STRING ? cell.getStringCellValue() : cell.getCellType() == Cell.CELL_TYPE_BLANK ? cell.getStringCellValue() : cell.getCellType() == Cell.CELL_TYPE_ERROR ? cell.getErrorCellValue() : cell.getCellType() == Cell.CELL_TYPE_FORMULA ? cell.getCachedFormulaResultType() : cell.getStringCellValue(); }
From source file:com.kybelksties.excel.ExcelSheetTableModel.java
License:Open Source License
/** * Insert a row at a given index./*from w ww . j a v a2 s. c om*/ * * @param createAtIndex row-number of the cell at which to create a new row * @param sourceRow the row to insert */ public void insertRowAt(int createAtIndex, Row sourceRow) { Row newRow = getRow(createAtIndex); if (newRow != null) { // shift all rows >= createAtIndex up by one getSheet().shiftRows(createAtIndex, getSheet().getLastRowNum(), 1); } else { newRow = getSheet().createRow(createAtIndex); } // Loop through source columns to add to new row for (int i = 0; i < sourceRow.getLastCellNum(); i++) { // Grab a copy of the old/new cell Cell oldCell = sourceRow.getCell(i); Cell newCell = newRow.createCell(i); // If the old cell is null jump to next cell if (oldCell == null) { continue; } // Copy style from old cell and apply to new cell CellStyle newCellStyle = workbook.createCellStyle(); newCellStyle.cloneStyleFrom(oldCell.getCellStyle()); newCell.setCellStyle(newCellStyle); // If there is a cell comment, copy if (oldCell.getCellComment() != null) { newCell.setCellComment(oldCell.getCellComment()); } // If there is a cell hyperlink, copy if (oldCell.getHyperlink() != null) { newCell.setHyperlink(oldCell.getHyperlink()); } // Set the cell data type newCell.setCellType(oldCell.getCellType()); // Set the cell data value switch (oldCell.getCellType()) { case Cell.CELL_TYPE_BLANK: newCell.setCellValue(oldCell.getStringCellValue()); break; case Cell.CELL_TYPE_BOOLEAN: newCell.setCellValue(oldCell.getBooleanCellValue()); break; case Cell.CELL_TYPE_ERROR: newCell.setCellErrorValue(oldCell.getErrorCellValue()); break; case Cell.CELL_TYPE_FORMULA: newCell.setCellFormula(oldCell.getCellFormula()); break; case Cell.CELL_TYPE_NUMERIC: newCell.setCellValue(oldCell.getNumericCellValue()); break; case Cell.CELL_TYPE_STRING: newCell.setCellValue(oldCell.getRichStringCellValue()); break; } } // If there are are any merged regions in the source row, copy to new row for (int i = 0; i < getSheet().getNumMergedRegions(); i++) { CellRangeAddress cellRangeAddress = getSheet().getMergedRegion(i); if (cellRangeAddress.getFirstRow() == sourceRow.getRowNum()) { CellRangeAddress newCellRangeAddress = new CellRangeAddress(newRow.getRowNum(), (newRow.getRowNum() + (cellRangeAddress.getLastRow() - cellRangeAddress.getFirstRow())), cellRangeAddress.getFirstColumn(), cellRangeAddress.getLastColumn()); getSheet().addMergedRegion(newCellRangeAddress); } } }
From source file:com.larasolution.serverlts.FileUploadHandler.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // tablename=request.getParameter(tablename) //process only if its multipart content FileOutputStream fos = new FileOutputStream("C:\\uploads\\data.csv"); String list = ""; List<List> allData = new ArrayList<List>(); List<String> parameters = new ArrayList<String>(); if (ServletFileUpload.isMultipartContent(request)) { try {//from ww w. j a v a 2 s. c o m StringBuilder data = new StringBuilder(); List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); System.out.println(multiparts); for (FileItem item : multiparts) { if (item.isFormField()) { parameters.add(item.getFieldName()); System.out.println(parameters); } if (!item.isFormField()) { String name = new File(item.getName()).getName(); item.write(new File(UPLOAD_DIRECTORY + File.separator + name)); //System.out.println(File.separator); // Get the workbook object for XLSX file XSSFWorkbook wBook = new XSSFWorkbook( new FileInputStream(UPLOAD_DIRECTORY + File.separator + name)); XSSFSheet zz = wBook.getSheetAt(0); FormulaEvaluator formulaEval = wBook.getCreationHelper().createFormulaEvaluator(); Row row; Cell cell; // Iterate through each rows from first sheet Iterator<Row> rowIterator = zz.iterator(); while (rowIterator.hasNext()) { row = rowIterator.next(); // For each row, iterate through each columns Iterator<Cell> cellIterator = row.cellIterator(); while (cellIterator.hasNext()) { cell = cellIterator.next(); switch (cell.getCellType()) { case Cell.CELL_TYPE_BOOLEAN: data.append(cell.getBooleanCellValue()).append(","); break; case Cell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(cell)) { data.append( com.larasolution.modle.getDate.getDate5(cell.getDateCellValue())) .append(","); } else { data.append(cell.getNumericCellValue()).append(","); } break; case Cell.CELL_TYPE_STRING: data.append(cell.getStringCellValue()).append(","); break; case Cell.CELL_TYPE_BLANK: data.append("" + ","); break; case Cell.CELL_TYPE_FORMULA: Double value = Double.parseDouble(formulaEval.evaluate(cell).formatAsString()); data.append(String.format("%.2f", value)).append(","); break; default: data.append(cell).append(""); } } data.append("\r\n"); //String k = data.substring(0, data.length() - 3); //ls.add(k); // data.setLength(0); } fos.write(data.toString().getBytes()); fos.close(); // } } savetosql(); request.setAttribute("message", "successfully uploaded "); } catch (Exception ex) { request.setAttribute("message", "File Upload Failed due to " + ex); } } else { request.setAttribute("message", "Sorry this Servlet only handles file upload request"); } request.setAttribute("arrayfile", allData); request.setAttribute("names", parameters); RequestDispatcher disp = getServletContext().getRequestDispatcher("/FileUploadResult.jsp"); disp.forward(request, response); // System.out.println(allData.size()); // response.sendRedirect("send.jsp?arrayfile=" + list + ""); //request.getRequestDispatcher("/send.jsp?arrayfile='"+ls+"'").forward(request, response); }
From source file:com.lushapp.common.excel.ExcelUtil.java
License:Apache License
/** * //from w ww.java2 s. com * excel * * @param inputstream : ? * @param pojoClass : (?) * @return */ public static Collection importExcelByIs(InputStream inputstream, Class pojoClass) { Collection dist = new ArrayList<Object>(); try { // Field filed[] = pojoClass.getDeclaredFields(); // Annotation??,map Map<String, Method> fieldSetMap = new HashMap<String, Method>(); Map<String, Method> fieldSetConvertMap = new HashMap<String, Method>(); // ? for (int i = 0; i < filed.length; i++) { Field f = filed[i]; // ?Annotation Excel excel = f.getAnnotation(Excel.class); // Annotationd? if (excel != null) { // AnnotationSetter String fieldname = f.getName(); String setMethodName = "set" + fieldname.substring(0, 1).toUpperCase() + fieldname.substring(1); // method Method setMethod = pojoClass.getMethod(setMethodName, new Class[] { f.getType() }); // methodAnnotaion??key? // ??? ?? fieldSetMap.put(excel.exportName(), setMethod); if (excel.importConvert() == true) { // get/setXxxxConvert??? ?Entity? StringBuffer setConvertMethodName = new StringBuffer("convertSet"); setConvertMethodName.append(fieldname.substring(0, 1).toUpperCase()); setConvertMethodName.append(fieldname.substring(1)); Method getConvertMethod = pojoClass.getMethod(setConvertMethodName.toString(), new Class[] { String.class }); fieldSetConvertMap.put(excel.exportName(), getConvertMethod); } } } // FileFileInputStream; // // HSSFWorkbook book = new HSSFWorkbook(inputstream); // // HSSFSheet sheet = book.getSheetAt(0); // // ? Iterator<Row> row = sheet.rowIterator(); // Row title = row.next(); // Iterator<Cell> cellTitle = title.cellIterator(); // map Map titlemap = new HashMap(); // int i = 0; // while (cellTitle.hasNext()) { Cell cell = cellTitle.next(); String value = cell.getStringCellValue(); titlemap.put(i, value); i = i + 1; } // ??DateFormat // SimpleDateFormat sf; while (row.hasNext()) { // Row rown = row.next(); // Iterator<Cell> cellbody = rown.cellIterator(); // Object tObject = pojoClass.newInstance(); int k = 0; // ?? while (cellbody.hasNext()) { Cell cell = cellbody.next(); // String titleString = (String) titlemap.get(k); // ?Annotation?set if (fieldSetMap.containsKey(titleString)) { Method setMethod = (Method) fieldSetMap.get(titleString); // setter? Type[] ts = setMethod.getGenericParameterTypes(); // ??? String xclass = ts[0].toString(); // ? if (Cell.CELL_TYPE_STRING == cell.getCellType() && fieldSetConvertMap.containsKey(titleString)) { // ???String? fieldSetConvertMap.get(titleString).invoke(tObject, cell.getStringCellValue()); } else { if (xclass.equals("class java.lang.String")) { // Cell??String? cell.setCellType(Cell.CELL_TYPE_STRING); setMethod.invoke(tObject, cell.getStringCellValue()); } else if (xclass.equals("class java.util.Date")) { // update-start--Author:Quainty Date:20130523 for??(?Excel?) Date cellDate = null; if (Cell.CELL_TYPE_NUMERIC == cell.getCellType()) { // ? cellDate = cell.getDateCellValue(); } else { // Cell.CELL_TYPE_STRING: ? yyyy-mm-dd hh:mm:ss ??(wait to do:?) cellDate = stringToDate(cell.getStringCellValue()); } setMethod.invoke(tObject, cellDate); //// -------------------------------------------------------------------------------------------- //String cellValue = cell.getStringCellValue(); //Date theDate = stringToDate(cellValue); //setMethod.invoke(tObject, theDate); //// -------------------------------------------------------------------------------------------- } else if (xclass.equals("class java.lang.Boolean")) { boolean valBool; if (Cell.CELL_TYPE_BOOLEAN == cell.getCellType()) { valBool = cell.getBooleanCellValue(); } else {// Cell.CELL_TYPE_STRING valBool = cell.getStringCellValue().equalsIgnoreCase("true") || (!cell.getStringCellValue().equals("0")); } setMethod.invoke(tObject, valBool); } else if (xclass.equals("class java.lang.Integer")) { Integer valInt; if (Cell.CELL_TYPE_NUMERIC == cell.getCellType()) { valInt = (new Double(cell.getNumericCellValue())).intValue(); } else {// Cell.CELL_TYPE_STRING valInt = new Integer(cell.getStringCellValue()); } setMethod.invoke(tObject, valInt); } else if (xclass.equals("class java.lang.Long")) { Long valLong; if (Cell.CELL_TYPE_NUMERIC == cell.getCellType()) { valLong = (new Double(cell.getNumericCellValue())).longValue(); } else {// Cell.CELL_TYPE_STRING valLong = new Long(cell.getStringCellValue()); } setMethod.invoke(tObject, valLong); } else if (xclass.equals("class java.math.BigDecimal")) { BigDecimal valDecimal; if (Cell.CELL_TYPE_NUMERIC == cell.getCellType()) { valDecimal = new BigDecimal(cell.getNumericCellValue()); } else {// Cell.CELL_TYPE_STRING valDecimal = new BigDecimal(cell.getStringCellValue()); } setMethod.invoke(tObject, valDecimal); } } } // k = k + 1; } dist.add(tObject); } } catch (Exception e) { e.printStackTrace(); return null; } return dist; }
From source file:com.maxl.java.aips2xml.Aips2Xml.java
License:Open Source License
static String getAnyValue(Cell part) { if (part != null) { switch (part.getCellType()) { case Cell.CELL_TYPE_BOOLEAN: return part.getBooleanCellValue() + ""; case Cell.CELL_TYPE_NUMERIC: return part.getNumericCellValue() + ""; case Cell.CELL_TYPE_STRING: return part.getStringCellValue() + ""; case Cell.CELL_TYPE_BLANK: return "BLANK"; case Cell.CELL_TYPE_ERROR: return "ERROR"; case Cell.CELL_TYPE_FORMULA: return "FORMEL"; }//w w w . j ava2 s . c o m } return ""; }
From source file:com.mimp.controllers.reporte.java
private static void copyRow(Sheet worksheet, int sourceRowNum, int destinationRowNum) { // Coge la fila antigua y nueva Row newRow = worksheet.getRow(destinationRowNum); Row sourceRow = worksheet.getRow(sourceRowNum); //Si existe una fila en el detino, pasa todas las filas 1 ms abajo antes de crear la nueva columna if (newRow != null) { worksheet.shiftRows(destinationRowNum, worksheet.getLastRowNum(), 1); } else {// ww w .ja va 2 s.c om newRow = worksheet.createRow(destinationRowNum); } // Hace un loop entre las celdas de cada columna para aadir una por una a la nueva for (int i = 0; i < sourceRow.getLastCellNum(); i++) { // Copia la antigua y nueva celda Cell oldCell = sourceRow.getCell(i); Cell newCell = newRow.createCell(i); // Si la anterior celda es null, evalua la siguiente celda defrente if (oldCell == null) { newCell = null; continue; } // Usa el estilo de la celda antigua newCell.setCellStyle(oldCell.getCellStyle()); // Establece el tipo de valor de la celda newCell.setCellType(oldCell.getCellType()); // Establece el valor de la celda switch (oldCell.getCellType()) { case Cell.CELL_TYPE_BLANK: break; case Cell.CELL_TYPE_BOOLEAN: newCell.setCellValue(oldCell.getBooleanCellValue()); break; case Cell.CELL_TYPE_ERROR: newCell.setCellErrorValue(oldCell.getErrorCellValue()); break; case Cell.CELL_TYPE_FORMULA: newCell.setCellFormula(oldCell.getCellFormula()); break; case Cell.CELL_TYPE_NUMERIC: newCell.setCellValue(oldCell.getNumericCellValue()); break; case Cell.CELL_TYPE_STRING: newCell.setCellValue(oldCell.getRichStringCellValue()); break; } } }
From source file:com.miraisolutions.xlconnect.data.ColumnBuilder.java
License:Open Source License
protected CellValue getCachedCellValue(Cell cell) { int valueType = cell.getCellType(); if (valueType == Cell.CELL_TYPE_FORMULA) { valueType = cell.getCachedFormulaResultType(); }/*ww w. j a v a2 s . c om*/ switch (valueType) { case Cell.CELL_TYPE_BLANK: return null; case Cell.CELL_TYPE_BOOLEAN: if (cell.getBooleanCellValue()) { return CellValue.TRUE; } else { return CellValue.FALSE; } case Cell.CELL_TYPE_NUMERIC: return new CellValue(cell.getNumericCellValue()); case Cell.CELL_TYPE_STRING: return new CellValue(cell.getStringCellValue()); case Cell.CELL_TYPE_ERROR: return CellValue.getError(cell.getErrorCellValue()); default: String msg = String.format("Could not extract value from cell with cached value type %d", valueType); throw new RuntimeException(msg); } }
From source file:com.movielabs.availslib.AvailSS.java
License:Open Source License
/** * Add a sheet from an Excel spreadsheet to a spreadsheet object * @param wb an Apache POI workbook object * @param sheet an Apache POI sheet object * @return created sheet object/*from w w w.j av a2s.com*/ */ private AvailsSheet addSheetHelper(Workbook wb, Sheet sheet) throws Exception { AvailsSheet as = new AvailsSheet(this, sheet.getSheetName()); // int qq = 0; for (Row row : sheet) { // qq++; int len = row.getLastCellNum(); if (len < 0) continue; String[] fields = new String[len]; for (int i = 0; i < len; i++) // XXX: don't want nulls fields[i] = ""; for (Cell cell : row) { int idx = cell.getColumnIndex(); int type = cell.getCellType(); switch (type) { case 0: // Numeric double v = cell.getNumericCellValue(); if (v < 0.5) { // XXX hack: assume TotalRunTime java.util.Date d = cell.getDateCellValue(); fields[idx] = String.format("%02d:%02d:%02d", d.getHours(), d.getMinutes(), d.getSeconds()); //System.out.println("run=" + tmp); } else { fields[idx] = cell.toString(); } break; case 1: // String case 3: // Blank fields[idx] = cell.getStringCellValue().trim(); break; default: //logger.warn("Cell[" + i + "," + idx + "]: invalid type (" + type + ")"); fields[idx] = cell.toString(); break; } } /* cell */ if (as.isAvail(fields)) as.addRow(fields, row.getRowNum() + 1); } /* row */ sheets.add(as); return as; }