List of usage examples for org.apache.poi.ss.usermodel Cell getDateCellValue
Date getDateCellValue();
From source file:gtu._work.ui.SqlCreaterUI.java
License:Open Source License
private String formatCellType(Cell cell) { String returnVal = StringUtils.EMPTY; if (cell == null) { return ""; }//from w w w . j a v a2 s .c om if (Cell.CELL_TYPE_NUMERIC == cell.getCellType()) { if (HSSFDateUtil.isCellDateFormatted(cell)) { Date d = cell.getDateCellValue(); returnVal = " to_date('" + SDF.format(d) + "', 'yyyymmdd' ) "; } else { final NumberFormat formatter = new DecimalFormat("##"); returnVal = formatter.format(Float.valueOf(cell.toString())); } } else { returnVal = cell.toString(); } return returnVal; }
From source file:helpers.Excel.ExcelDataFormat.java
public Object marshalAsArray(Iterator<Row> sheet) { ArrayList<ArrayList<Object>> results = new ArrayList<ArrayList<Object>>(); for (Iterator<Row> rowIterator = sheet; rowIterator.hasNext();) { ArrayList newrow = new ArrayList(); results.add(newrow);//from ww w . ja v a 2s. c o m Row row = rowIterator.next(); for (Iterator<Cell> cellIterator = row.cellIterator(); cellIterator.hasNext();) { Cell cell = cellIterator.next(); logger.info("Cell type:" + cell.getCellType()); switch (cell.getCellType()) { case HSSFCell.CELL_TYPE_NUMERIC: if (HSSFDateUtil.isCellDateFormatted(cell)) { //logger.info(cell.getCellType()+"="+cell.getDateCellValue()); newrow.add(cell.getDateCellValue()); } else { //logger.info(cell.getCellType()+"="+cell.getNumericCellValue()); newrow.add(cell.getNumericCellValue()); } break; default: //logger.info(cell.getCellType()+"="+cell.getStringCellValue()); newrow.add(cell.getStringCellValue()); break; } } } return results; }
From source file:helpers.Excel.ExcelDataFormat.java
public OneExcelSheet marshalAsStructure(Iterator<Row> sheet, FormulaEvaluator evaluator) { logger.info("Evaluating formulas."); evaluator.evaluateAll();/*from w ww . j a va 2 s . c o m*/ logger.info("Done..."); OneExcelSheet onesheet = new OneExcelSheet(); ArrayList<String> headers = null; for (Iterator<Row> rowIterator = sheet; rowIterator.hasNext();) { Row row = rowIterator.next(); if (headers == null) { headers = new ArrayList<String>(); int coln = 0; for (Iterator<Cell> cellIterator = row.cellIterator(); cellIterator.hasNext();) { try { Cell cell = cellIterator.next(); logger.info("Header:" + cell.getStringCellValue()); String headn = cell.getStringCellValue().replace(" ", ""); headers.add(headn); OneExcelColumn col = new OneExcelColumn(headn, coln); onesheet.columns.add(col); } catch (Exception e) { logger.error("Unable to decode cell header. Ex=" + e.getMessage(), e); } coln++; } } else { ArrayList<Object> newrow = new ArrayList<Object>(); onesheet.data.add(newrow); int coln = 0; //for (Iterator<Cell> cellIterator = row.cellIterator(); cellIterator.hasNext();) for (int cn = 0; cn < row.getLastCellNum(); cn++) { Cell cell = row.getCell(cn, Row.CREATE_NULL_AS_BLANK); //Cell cell=cellIterator.next(); //logger.info("Cell type:"+cell.getCellType()); switch (evaluator.evaluateInCell(cell).getCellType()) { case HSSFCell.CELL_TYPE_NUMERIC: if (HSSFDateUtil.isCellDateFormatted(cell)) { //logger.info(cell.getCellType()+"="+cell.getDateCellValue()); newrow.add(cell.getDateCellValue()); if (onesheet.columns.size() > coln) onesheet.columns.get(coln).columnTypes[9]++; } else { //logger.info(cell.getCellType()+"="+cell.getNumericCellValue()); newrow.add(cell.getNumericCellValue()); if (onesheet.columns.size() > coln) onesheet.columns.get(coln).columnTypes[cell.getCellType()]++; } break; case HSSFCell.CELL_TYPE_FORMULA: int value = evaluator.evaluateFormulaCell(cell); value = cell.getCachedFormulaResultType(); newrow.add(value); if (onesheet.columns.size() > coln) onesheet.columns.get(coln).columnTypes[0]++; break; default: //logger.info(cell.getCellType()+"="+cell.getStringCellValue()); String cellstr = new String(cell.getStringCellValue().getBytes(), Charset.forName("UTF-8")); newrow.add(cellstr); if (onesheet.columns.size() > coln) onesheet.columns.get(coln).columnTypes[cell.getCellType()]++; break; } coln++; } } } return onesheet; }
From source file:hjow.hgtable.util.XLSXUtil.java
License:Apache License
/** * <p>XLSX ? ? ?? . ? ? ?? ?? , ? ? ?? ? ? ?? ?.</p> * //ww w.j a v a2s . c o m * @param file : XLSX ? * @return ? ? */ public static List<TableSet> toTableSets(File file) { List<TableSet> tableSets = new Vector<TableSet>(); org.apache.poi.ss.usermodel.Workbook workbook = null; if (file == null) throw new NullPointerException(Manager.applyStringTable("Please select file !!")); if (!file.exists()) throw new NullPointerException(Manager.applyStringTable("File") + " " + file.getAbsolutePath() + " " + Manager.applyStringTable("is not exist")); boolean isHead = true; int rowNum = 0; int cellNum = 0; int cellCount = 0; FileInputStream fileStream = null; try { if (file.getAbsolutePath().endsWith(".xlsx") || file.getAbsolutePath().endsWith(".XLSX")) { workbook = new org.apache.poi.xssf.usermodel.XSSFWorkbook(file); } else if (file.getAbsolutePath().endsWith(".xls") || file.getAbsolutePath().endsWith(".XLS")) { fileStream = new FileInputStream(file); workbook = new org.apache.poi.hssf.usermodel.HSSFWorkbook(fileStream); } org.apache.poi.ss.usermodel.FormulaEvaluator evals = workbook.getCreationHelper() .createFormulaEvaluator(); org.apache.poi.ss.usermodel.Sheet sheet = null; for (int x = 0; x < workbook.getNumberOfSheets(); x++) { TableSet newTableSet = new DefaultTableSet(); newTableSet.setColumns(new Vector<Column>()); sheet = workbook.getSheetAt(x); newTableSet.setName(sheet.getSheetName()); rowNum = 0; isHead = true; String targetData = null; for (org.apache.poi.ss.usermodel.Row row : sheet) { cellNum = 0; for (org.apache.poi.ss.usermodel.Cell cell : row) { try { if (cellNum >= cellCount) { throw new IndexOutOfBoundsException( Manager.applyStringTable("There are some cells not have their heads") + ", " + Manager.applyStringTable("Head count") + " : " + cellCount + ", " + Manager.applyStringTable("Cell Number") + " : " + cellNum); } switch (cell.getCellType()) { case org.apache.poi.ss.usermodel.Cell.CELL_TYPE_STRING: if (isHead) { newTableSet.getColumns().add(new Column( cell.getRichStringCellValue().getString(), Column.TYPE_STRING)); } else { targetData = cell.getRichStringCellValue().getString(); newTableSet.getColumns().get(cellNum).setType(cell.getCellType()); } break; case org.apache.poi.ss.usermodel.Cell.CELL_TYPE_NUMERIC: if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) { if (isHead) { newTableSet.getColumns().add(new Column( String.valueOf(cell.getStringCellValue()), Column.TYPE_DATE)); } else { targetData = String.valueOf(cell.getDateCellValue()); newTableSet.getColumns().get(cellNum).setType(cell.getCellType()); } } else { if (isHead) { newTableSet.getColumns().add(new Column( String.valueOf(cell.getStringCellValue()), Column.TYPE_NUMERIC)); } else { double values = cell.getNumericCellValue(); double intPart = values - ((double) ((int) values)); if (intPart == 0.0) { targetData = String.valueOf(((int) values)); newTableSet.getColumns().get(cellNum).setType(Column.TYPE_INTEGER); } else { targetData = String.valueOf(values); newTableSet.getColumns().get(cellNum).setType(cell.getCellType()); } } } break; case org.apache.poi.ss.usermodel.Cell.CELL_TYPE_BOOLEAN: if (isHead) { newTableSet.getColumns().add(new Column( String.valueOf(cell.getStringCellValue()), Column.TYPE_BOOLEAN)); } else { targetData = String.valueOf(cell.getBooleanCellValue()); newTableSet.getColumns().get(cellNum).setType(cell.getCellType()); } break; case org.apache.poi.ss.usermodel.Cell.CELL_TYPE_FORMULA: if (isHead) { newTableSet.getColumns().add(new Column( String.valueOf(cell.getStringCellValue()), Column.TYPE_NUMERIC)); } else { if (evals.evaluateFormulaCell(cell) == 0) { targetData = String.valueOf(cell.getNumericCellValue()); newTableSet.getColumns().get(cellNum).setType(Column.TYPE_NUMERIC); } else if (evals.evaluateFormulaCell(cell) == 1) { targetData = String.valueOf(cell.getStringCellValue()); newTableSet.getColumns().get(cellNum).setType(Column.TYPE_STRING); } else if (evals.evaluateFormulaCell(cell) == 4) { targetData = String.valueOf(cell.getBooleanCellValue()); newTableSet.getColumns().get(cellNum).setType(Column.TYPE_BOOLEAN); } else { targetData = String.valueOf(cell.getCellFormula()); newTableSet.getColumns().get(cellNum).setType(cell.getCellType()); } } break; case org.apache.poi.ss.usermodel.Cell.CELL_TYPE_BLANK: if (isHead) { newTableSet.getColumns().add(new Column("", Column.TYPE_STRING)); } else { targetData = ""; newTableSet.getColumns().get(cellNum).setType(Column.TYPE_BLANK); } break; default: if (isHead) { newTableSet.getColumns().add(new Column("", Column.TYPE_STRING)); } else { try { targetData = cell.getStringCellValue(); } catch (Exception e1) { e1.printStackTrace(); } newTableSet.getColumns().get(cellNum).setType(cell.getCellType()); } break; } if (isHead) { cellCount++; } else { while (rowNum > 0 && newTableSet.getColumns().get(cellNum).getData().size() < rowNum) { newTableSet.getColumns().get(cellNum).getData().add(""); } if (targetData != null) newTableSet.getColumns().get(cellNum).getData().add(targetData); else { newTableSet.getColumns().get(cellNum).getData().add(""); } } } catch (ArrayIndexOutOfBoundsException e1) { StringBuffer err = new StringBuffer(""); for (StackTraceElement errEl : e1.getStackTrace()) { err = err.append("\t " + errEl + "\n"); } String cellObject = null; try { cellObject = cell.getStringCellValue(); } catch (Exception e2) { } throw new ArrayIndexOutOfBoundsException( Manager.applyStringTable("Array index out of range") + " <- " + Manager.applyStringTable("Reading xlsx file") + " : " + file.getName() + ", " + sheet.getSheetName() + "\n" + Manager.applyStringTable("On") + " " + Manager.applyStringTable("Row") + " " + rowNum + ", " + Manager.applyStringTable("Cell") + " " + cellNum + ", " + Manager.applyStringTable("Value") + " : " + String.valueOf(cellObject) + "\n " + Manager.applyStringTable("<-\n") + err + "\n " + Manager.applyStringTable("Original Message") + "...\n" + e1.getMessage() + "\n" + Manager.applyStringTable("End")); } cellNum++; } isHead = false; rowNum++; } fillTableSet(newTableSet); newTableSet.removeEmptyColumn(true); tableSets.add(newTableSet); } return tableSets; } catch (Throwable e) { if (Main.MODE >= DebuggingUtil.DEBUG) e.printStackTrace(); Main.logError(e, Manager.applyStringTable("On reading xlsx") + " : " + file + "\n" + Manager.applyStringTable("At rownum") + " " + rowNum + ", " + Manager.applyStringTable("cellnum") + " " + cellNum); return null; } finally { try { workbook.close(); } catch (Throwable e) { } try { if (fileStream != null) fileStream.close(); } catch (Throwable e) { } } }
From source file:it.dontesta.liferay.example.portal.client.ImportUsersToLiferay.java
License:Open Source License
/** * Read users to import from excel file. * /* w ww .j a v a 2s. co m*/ * @return Returns a list of users who are ready for import. */ private static List<UserToImport> getUsersToImportFromExcel() { String fileName = (System.getProperty("fileToImport") != null) ? System.getProperty("fileToImport") : FILE_TO_IMPORT_USERS; InputStream inp = null; List<UserToImport> usersList = new ArrayList<UserToImport>(); UserToImport user = null; boolean readyForImport = true; try { inp = new FileInputStream(fileName); Workbook wb = WorkbookFactory.create(inp); Sheet sheet = wb.getSheetAt(0); for (Row row : sheet) { LOGGER.debug("Processing row index {}...", row.getRowNum()); if (row.getRowNum() == 0) { LOGGER.debug("First row is the header. Skip this row"); continue; } else { user = new UserToImport(); } for (Cell cell : row) { LOGGER.debug("Processing cell index {}...", cell.getColumnIndex()); switch (cell.getColumnIndex()) { case 0: if (!cell.getStringCellValue().isEmpty()) { user.setTitle(cell.getStringCellValue()); LOGGER.debug("Value cell index {} is {}", cell.getColumnIndex(), cell.getStringCellValue()); } LOGGER.debug("Processing cell index {}...[OK]", cell.getColumnIndex()); break; case 1: if (!cell.getStringCellValue().isEmpty()) { user.setScreenName(cell.getStringCellValue()); LOGGER.debug("Value cell index {} is {}", cell.getColumnIndex(), cell.getStringCellValue()); } else { LOGGER.warn("The username attribute is not null. Row skipped"); LOGGER.warn("Processing cell index {}...[FAILED]", cell.getColumnIndex()); break; } LOGGER.debug("Processing cell index {}...[OK]", cell.getColumnIndex()); break; case 2: if (!cell.getStringCellValue().isEmpty()) { user.setEmail(cell.getStringCellValue()); LOGGER.debug("Value cell index {} is {}", cell.getColumnIndex(), cell.getStringCellValue()); } else { LOGGER.warn("The email attribute is not null. Row skipped"); LOGGER.warn("Processing cell index {}...[FAILED]", cell.getColumnIndex()); break; } LOGGER.debug("Processing cell index {}...[OK]", cell.getColumnIndex()); break; case 3: if (!cell.getStringCellValue().isEmpty()) { user.setFirstName(cell.getStringCellValue()); LOGGER.debug("Value cell index {} is {}", cell.getColumnIndex(), cell.getStringCellValue()); } LOGGER.debug("Processing cell index {}...[OK]", cell.getColumnIndex()); break; case 4: if (!cell.getStringCellValue().isEmpty()) { user.setMiddleName(cell.getStringCellValue()); LOGGER.debug("Value cell index {} is {}", cell.getColumnIndex(), cell.getStringCellValue()); } LOGGER.debug("Processing cell index {}...[OK]", cell.getColumnIndex()); break; case 5: if (!cell.getStringCellValue().isEmpty()) { user.setLastName(cell.getStringCellValue()); LOGGER.debug("Value cell index {} is {}", cell.getColumnIndex(), cell.getStringCellValue()); } LOGGER.debug("Processing cell index {}...[OK]", cell.getColumnIndex()); break; case 6: if (!cell.getStringCellValue().isEmpty()) { user.setGender(cell.getStringCellValue()); LOGGER.debug("Value cell index {} is {}", cell.getColumnIndex(), cell.getStringCellValue()); } LOGGER.debug("Processing cell index {}...[OK]", cell.getColumnIndex()); break; case 7: if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) { if (DateUtil.isCellDateFormatted(cell)) { Calendar calBirthDate = Calendar.getInstance(); calBirthDate.setTime(cell.getDateCellValue()); user.setBirthDate(calBirthDate); LOGGER.debug("Value cell index {} is {}", cell.getColumnIndex(), cell.getDateCellValue()); } else { LOGGER.warn("Value cell index {} {}", cell.getColumnIndex(), cell.getNumericCellValue()); LOGGER.warn("Value cell index {} not contain a date type format", cell.getColumnIndex()); } } LOGGER.debug("Processing cell index {}...[OK]", cell.getColumnIndex()); break; case 8: if (!cell.getStringCellValue().isEmpty()) { user.setJobTitle(cell.getStringCellValue()); LOGGER.debug("Value cell index {} is {}", cell.getColumnIndex(), cell.getStringCellValue()); } break; case 9: if (!cell.getStringCellValue().isEmpty()) { user.setSiteName(cell.getStringCellValue().split(",")); LOGGER.debug("Value cell index {} is {}", cell.getColumnIndex(), Arrays.toString(cell.getStringCellValue().split(","))); } LOGGER.debug("Processing cell index {}...[OK]", cell.getColumnIndex()); break; case 10: if (!cell.getStringCellValue().isEmpty()) { user.setRoleName(cell.getStringCellValue().split(",")); LOGGER.debug("Value cell index {} is {}", cell.getColumnIndex(), Arrays.toString(cell.getStringCellValue().split(","))); } LOGGER.debug("Processing cell index {}...[OK]", cell.getColumnIndex()); break; case 11: if (!cell.getStringCellValue().isEmpty()) { user.setLanguageId(cell.getStringCellValue()); LOGGER.debug("Value cell index {} is {}", cell.getColumnIndex(), cell.getStringCellValue()); } LOGGER.debug("Processing cell index {}...[OK]", cell.getColumnIndex()); break; case 12: if (!cell.getStringCellValue().isEmpty()) { user.setTimeZoneId(cell.getStringCellValue()); LOGGER.debug("Value cell index {} is {}", cell.getColumnIndex(), cell.getStringCellValue()); } LOGGER.debug("Processing cell index {}...[OK]", cell.getColumnIndex()); break; case 13: if (!cell.getStringCellValue().isEmpty()) { user.setAccountId(cell.getStringCellValue()); LOGGER.debug("Value cell index {} is {}", cell.getColumnIndex(), cell.getStringCellValue()); } LOGGER.debug("Processing cell index {}...[OK]", cell.getColumnIndex()); break; default: break; } } if (user.getScreenName() == null) { LOGGER.warn("The username attribute can not be null for rowId {}", row.getRowNum()); readyForImport = false; } if (user.getEmail() == null) { LOGGER.warn("The email attribute can not be null for rowId {}", row.getRowNum()); readyForImport = false; } if (readyForImport) { LOGGER.info("Add user object {} to user list...", user.toString()); usersList.add(user); } } } catch (FileNotFoundException e) { LOGGER.error(e.getMessage()); } catch (IllegalStateException e) { LOGGER.error(e.getMessage()); } catch (InvalidFormatException e) { LOGGER.error(e.getMessage()); } catch (IOException e) { LOGGER.error(e.getMessage()); } return usersList; }
From source file:it.redev.parco.utils.ExcelUtils.java
License:Open Source License
public static Date getAsDate(Cell cell, String format) throws ParseException { if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) { return cell.getDateCellValue(); }// w ww. j a v a2s. c om return DateUtils.parse(ExcelUtils.getCellValue(cell), format); }
From source file:it.smartcommunitylab.riciclo.app.importer.converter.DataImporter.java
License:Apache License
private String getCellValue(Cell cell) { switch (cell.getCellType()) { case Cell.CELL_TYPE_STRING: return cell.getStringCellValue(); case Cell.CELL_TYPE_NUMERIC: String value;//w w w . ja va 2 s .co m Calendar cal = new GregorianCalendar(); cal.setTime(cell.getDateCellValue()); if (cal.get(Calendar.YEAR) < 2014) { value = cal.get(Calendar.HOUR_OF_DAY) + ":" + (cal.get(Calendar.MINUTE) + "0").substring(0, 2); } else { String month = "0" + (1 + cal.get(Calendar.MONTH)); String day = "0" + cal.get(Calendar.DAY_OF_MONTH); value = cal.get(Calendar.YEAR) + "-" + month.substring(month.length() - 2, month.length()) + "-" + day.substring(day.length() - 2, day.length()); } return value; } return ""; }
From source file:it.smartcommunitylab.ungiorno.importer.Importer.java
License:Apache License
private String getCellValue(Cell cell, String key) { switch (cell.getCellType()) { case Cell.CELL_TYPE_STRING: return cell.getStringCellValue(); case Cell.CELL_TYPE_NUMERIC: if (key != null && numFields.contains(key.toUpperCase())) { double v = cell.getNumericCellValue(); if (v - Math.floor(v) > 0) return "" + v; return "" + Math.round(v); }/* ww w . ja v a 2s. c o m*/ Date date = cell.getDateCellValue(); Calendar cal = Calendar.getInstance(); cal.setTime(date); if (cal.get(Calendar.YEAR) <= 1970) return TIME_FORMAT.format(date); return DATE_FORMAT.format(date); // TODO revise date management // String value = null; // Calendar cal = new GregorianCalendar(); // cal.setTime(cell.getDateCellValue()); // if (cal.get(Calendar.YEAR) < 2014) { // value = cal.get(Calendar.HOUR_OF_DAY) + ":" + (cal.get(Calendar.MINUTE) + "0").substring(0, 2); // } else { // String month = "0" + (1 + cal.get(Calendar.MONTH)); // String day = "0" + cal.get(Calendar.DAY_OF_MONTH); // value = cal.get(Calendar.YEAR) + "-" + month.substring(month.length() - 2, month.length()) + "-" + day.substring(day.length() - 2, day.length()); // } // return value; } return ""; }
From source file:javacommon.excel.ExcelReader.java
/** * ???/*from www . jav a 2 s . co m*/ * * @param c ? * @return */ private String getCellStringValue(Cell c) { if (c == null) { return ""; } String value = null; NumberFormat nf = NumberFormat.getInstance(); nf.setGroupingUsed(false); nf.setMaximumFractionDigits(12); switch (c.getCellType()) { case Cell.CELL_TYPE_BOOLEAN: value = String.valueOf(c.getBooleanCellValue()); break; case Cell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(c)) { return DateFormatUtils.ISO_DATE_FORMAT.format(c.getDateCellValue()); } else if ("@".equals(c.getCellStyle().getDataFormatString())) { value = nf.format(c.getNumericCellValue()); } else if ("General".equals(c.getCellStyle().getDataFormatString())) { value = nf.format(c.getNumericCellValue()); } else if (ArrayUtils.contains(ExcelConstants.DATE_PATTERNS, c.getCellStyle().getDataFormatString())) { value = DateFormatUtils.format(HSSFDateUtil.getJavaDate(c.getNumericCellValue()), c.getCellStyle().getDataFormatString()); } else { value = nf.format(c.getNumericCellValue()); } break; case Cell.CELL_TYPE_STRING: value = c.getStringCellValue(); break; case Cell.CELL_TYPE_FORMULA: value = c.getCellFormula(); break; } return value == null ? "" : value.trim(); }
From source file:javacommon.excel.ExcelReader.java
/** * ???//from ww w . j ava2s . c o m * * @param c ? * @return */ private String getCellStringFormatValue(Cell c) { if (c == null) { return ""; } String value = null; NumberFormat nf = NumberFormat.getInstance(); nf.setGroupingUsed(false); nf.setMaximumFractionDigits(12); switch (c.getCellType()) { case Cell.CELL_TYPE_BOOLEAN: value = String.valueOf(c.getBooleanCellValue()); break; case Cell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(c)) { return DateFormatUtils.ISO_DATE_FORMAT.format(c.getDateCellValue()); } else if ("@".equals(c.getCellStyle().getDataFormatString())) { value = nf.format(c.getNumericCellValue()); } else if ("General".equals(c.getCellStyle().getDataFormatString())) { value = nf.format(c.getNumericCellValue()); } else if (ArrayUtils.contains(ExcelConstants.DATE_PATTERNS, c.getCellStyle().getDataFormatString())) { value = DateFormatUtils.format(HSSFDateUtil.getJavaDate(c.getNumericCellValue()), c.getCellStyle().getDataFormatString()); } else { value = nf.format(c.getNumericCellValue()); } break; case Cell.CELL_TYPE_STRING: value = c.getStringCellValue(); break; case Cell.CELL_TYPE_FORMULA: return c.getCellFormula(); } return value == null ? "" : value.trim(); }