List of usage examples for org.apache.poi.ss.usermodel Row getRowNum
int getRowNum();
From source file:com.avaya.plds.excel.ExcelRead.java
public List<String> getPoeticFeatureLoad(String value1, String value2, int sheetNo, int headers) { System.out.println(" Inside of getPoeticFeatureLoad method ..."); sheet = xssfWorkbook.getSheetAt(sheetNo); boolean read = false; List<String> dataList = new ArrayList<String>(); rowIterator = sheet.iterator();// w w w . j av a2s .c om while (rowIterator.hasNext()) { StringBuilder builder = new StringBuilder(); Row row = rowIterator.next(); int rowNumber = row.getRowNum(); if (row != null) { for (short i = row.getFirstCellNum(); i < row.getLastCellNum(); i++) { if (row.getCell(i) != null && (row.getCell(i).getCellType() == row.getCell(i).CELL_TYPE_STRING) && row.getCell(i).getStringCellValue().contains(value1) && i == 0) { read = true; break; //builder.append(value1).append("\t"); } else if (row.getCell(i) != null && (row.getCell(i).getCellType() == row.getCell(i).CELL_TYPE_STRING) && row.getCell(i).getStringCellValue().contains(value2)) { read = false; } else if (read) { // System.out.println("rowNumber "+ rowNumber); maxCellIndex = (row.getLastCellNum() > maxCellIndex && rowNumber > 0) ? row.getLastCellNum() : maxCellIndex; // System.out.println("maxCellIndex "+ maxCellIndex); Cell cell = row.getCell(i); if (cell != null) { if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) { //if(i >0) builder.append( cell != null ? Double.valueOf(cell.getNumericCellValue()).longValue() : "") .append("\t"); } else { //if(i >0 ) builder.append(cell != null ? cell.getStringCellValue() : "").append("\t"); } } else { //if(i >0) builder.append("").append("\t"); } } if (headers == rowNumber) { //if(i>0) builder.append(row.getCell(i).getStringCellValue()).append("\t"); } } if (!builder.toString().equals("") && !builder.toString().matches("^ null.*")) dataList.add(builder.toString().replaceFirst(",", "")); } } return dataList; }
From source file:com.axelor.apps.admin.service.ViewDocExportService.java
License:Open Source License
private void updateDocMap(MetaFile docFile) { try {// w w w . j a v a2 s .c o m File doc = MetaFiles.getPath(docFile).toFile(); FileInputStream inSteam = new FileInputStream(doc); XSSFWorkbook book = new XSSFWorkbook(inSteam); oldBook = book; for (XSSFSheet sheet : book) { String lastKey = sheet.getSheetName(); Iterator<Row> rowIter = sheet.rowIterator(); while (rowIter.hasNext()) { Row row = rowIter.next(); String key = null; if (row.getRowNum() == 0) { key = sheet.getSheetName(); } else { String name = getCellValue(row.getCell(4)); if (Strings.isNullOrEmpty(name)) { name = getCellValue(row.getCell(5)); } String type = getCellValue(row.getCell(3)); if (type == null) { continue; } type = type.trim(); key = getCellValue(row.getCell(1)) + "," + getCellValue(row.getCell(2)) + "," + type + "," + name; if (addComment(lastKey, type, row)) { continue; } else { lastKey = key; } } docMap.put(key, row.getRowNum()); } } } catch (IOException e) { e.printStackTrace(); } }
From source file:com.axelor.apps.admin.service.ViewDocExportService.java
License:Open Source License
private boolean addComment(String lastKey, String type, Row row) { String mType = type;/*from w ww . j a v a 2 s .c o m*/ if (type.contains("(")) { mType = type.substring(0, type.indexOf("(")); mType = mType.replace("-", "_"); } if (!fieldTypes.contains(mType)) { Cell firstCell = row.getCell(0); if (firstCell != null) { List<Integer> rowIndexs = new ArrayList<Integer>(); if (commentMap.containsKey(lastKey)) { rowIndexs = commentMap.get(lastKey); } rowIndexs.add(row.getRowNum()); commentMap.put(lastKey, rowIndexs); return true; } } return false; }
From source file:com.bayareasoftware.chartengine.ds.util.ExcelInference.java
License:Apache License
private int getDataRowNum() { Iterator<Row> rows = sheet.rowIterator(); Row firstRow = null; int matched = 0; int i = 0;/*from www . ja v a2 s. co m*/ while (rows.hasNext()) { Row row = rows.next(); //eval.setCurrentRow(row); // Workaround for forumula evaluator bug //p("looking at row " + row.getRowNum()); if (firstRow == null) { if (hasNumericCell(row)/* && (md == null || hasMetadata(row, md))*/) { //p("proposing row #" + i + " as 1st data row..."); firstRow = row; matched = 0; } } else if (!match(row, firstRow)) { firstRow = null; } else if (++matched >= 2) { return firstRow.getRowNum(); } i++; } return -1; }
From source file:com.beyondb.io.ExcelControl.java
@Override public Object[][] readTableContent() throws IOException, InvalidFormatException, Exception { try {//from w w w .j av a 2s . co m //OPCPackage pkg = OPCPackage.open(file); // InputStream m_InputStream = new FileInputStream(m_File); Sheet sheet = null; // if (!m_InputStream.markSupported()) { // m_InputStream = new PushbackInputStream(m_InputStream, 8); // } // if (POIFSFileSystem.hasPOIFSHeader(m_InputStream)) { // HSSFWorkbook hSSFWorkbook = new HSSFWorkbook(m_InputStream); // sheet = (Sheet)hSSFWorkbook.getSheetAt(0); // // } else if (POIXMLDocument.hasOOXMLHeader(m_InputStream)) { // XSSFWorkbook xSSFWorkbook = new XSSFWorkbook(OPCPackage.open(m_File)); // sheet = (Sheet)xSSFWorkbook.getSheetAt(0); // } // else { // throw new IllegalArgumentException("excel?poi??"); // } sheet = getSheet(); if (sheet != null) { if (sheet.getLastRowNum() == 0) { throw new Exception("Excel"); } //? m_RowNum = sheet.getLastRowNum() + 1; // m_ColumnNum = sheet.getRow(0).getPhysicalNumberOfCells(); m_ColumnNum = sheet.getRow(0).getLastCellNum(); m_TableStr = new Object[m_RowNum][m_ColumnNum]; for (int rindex = 0; rindex < m_RowNum; rindex++) { Row row = sheet.getRow(rindex); for (int cindex = 0; cindex < m_ColumnNum; cindex++) { Cell cell = row.getCell(cindex); if (cell == null) { m_TableStr[rindex][cindex] = ""; } else { String value = ""; switch (cell.getCellType()) { case Cell.CELL_TYPE_STRING: // System.out.println(cell.getRichStringCellValue().getString()); value = cell.getRichStringCellValue().getString().replace("\n", ""); break; case Cell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(cell)) { // System.out.println(cell.getDateCellValue()); value = cell.getDateCellValue().toString(); } else { DecimalFormat df = new DecimalFormat("#"); value = String.valueOf(cell.getNumericCellValue()); double d = cell.getNumericCellValue(); int dInt = (int) d; BigDecimal b1 = new BigDecimal(value); BigDecimal b2 = new BigDecimal(Integer.toString(dInt)); double dPoint = b1.subtract(b2).doubleValue(); if (dPoint == 0) { //? value = df.format(cell.getNumericCellValue()); } } break; case Cell.CELL_TYPE_BOOLEAN: // System.out.println(cell.getBooleanCellValue()); value = cell.getBooleanCellValue() + ""; break; case Cell.CELL_TYPE_FORMULA: // System.out.println(cell.getCellFormula()); value = cell.getCellFormula(); break; case Cell.CELL_TYPE_BLANK: value = ""; default: // System.out.println(); value = ""; } m_TableStr[row.getRowNum()][cell.getColumnIndex()] = value; } } } } } catch (IOException | InvalidFormatException e) { Logger.getLogger(ExcelControl.class.getName()).log(Level.SEVERE, "excel??", e); throw e; } catch (Exception ex) { Logger.getLogger(ExcelControl.class.getName()).log(Level.SEVERE, "excel??", ex); throw ex; } finally { m_InputStream.close(); } return m_TableStr; }
From source file:com.blackducksoftware.tools.commonframework.standard.protex.report.template.TemplateWriter.java
License:Apache License
/** * Handles copying the formula for the provided sheet and active row * /*w w w .ja va 2 s .com*/ * @param sheet * the provided sheet * @param targetCell * the target cell to copy the formula * @param activeRow * the active row * @param column * the TemplateColumn to be used for */ private void copyFormula(Sheet sheet, Cell targetCell, Row activeRow, TemplateColumn column) { if (targetCell == null || sheet == null || targetCell.getCellType() != Cell.CELL_TYPE_FORMULA) { return; } String formula = column.getCellFormula(); int shiftRows = activeRow.getRowNum() - 1; int shiftCols = 0; XSSFEvaluationWorkbook workbookWrapper = XSSFEvaluationWorkbook.create((XSSFWorkbook) sheet.getWorkbook()); Ptg[] ptgs = FormulaParser.parse(formula, workbookWrapper, FormulaType.CELL, sheet.getWorkbook().getSheetIndex(sheet)); for (Ptg ptg : ptgs) { if (ptg instanceof RefPtgBase) { RefPtgBase ref = (RefPtgBase) ptg; if (ref.isColRelative()) { ref.setColumn(ref.getColumn() + shiftCols); } if (ref.isRowRelative()) { ref.setRow(ref.getRow() + shiftRows); } } else if (ptg instanceof AreaPtg) { AreaPtg ref = (AreaPtg) ptg; if (ref.isFirstColRelative()) { ref.setFirstColumn(ref.getFirstColumn() + shiftCols); } if (ref.isLastColRelative()) { ref.setLastColumn(ref.getLastColumn() + shiftCols); } if (ref.isFirstRowRelative()) { ref.setFirstRow(ref.getFirstRow() + shiftRows); } if (ref.isLastRowRelative()) { ref.setLastRow(ref.getLastRow() + shiftRows); } } } formula = FormulaRenderer.toFormulaString(workbookWrapper, ptgs); targetCell.setCellFormula(formula); log.debug("Set Formula for row " + activeRow.getRowNum() + " : " + formula); targetCell.setAsActiveCell(); }
From source file:com.bright.json.PGS.java
License:Open Source License
public static void main(String[] args) throws FileNotFoundException { String fileBasename = null;/*from w w w. j a va 2 s . c o m*/ JFileChooser chooser = new JFileChooser(); try { FileNameExtensionFilter filter = new FileNameExtensionFilter("Excel Spreadsheets", "xls", "xlsx"); chooser.setFileFilter(filter); chooser.setCurrentDirectory(new java.io.File(System.getProperty("user.home"))); chooser.setDialogTitle("Select the Excel file"); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); chooser.setAcceptAllFileFilterUsed(false); if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { System.out.println("getCurrentDirectory(): " + chooser.getCurrentDirectory()); System.out.println("getSelectedFile() : " + chooser.getSelectedFile()); // String fileBasename = // chooser.getSelectedFile().toString().substring(chooser.getSelectedFile().toString().lastIndexOf(File.separator)+1,chooser.getSelectedFile().toString().lastIndexOf(".")); fileBasename = chooser.getSelectedFile().toString() .substring(chooser.getSelectedFile().toString().lastIndexOf(File.separator) + 1); System.out.println("Base name: " + fileBasename); } else { System.out.println("No Selection "); } } catch (Exception e) { System.out.println(e.toString()); } String fileName = chooser.getSelectedFile().toString(); InputStream inp = new FileInputStream(fileName); Workbook workbook = null; if (fileName.toLowerCase().endsWith("xlsx")) { try { workbook = new XSSFWorkbook(inp); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (fileName.toLowerCase().endsWith("xls")) { try { workbook = new HSSFWorkbook(inp); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } Sheet nodeSheet = workbook.getSheet("Devices"); Sheet interfaceSheet = workbook.getSheet("Interfaces"); System.out.println("Read nodes sheet."); // Row nodeRow = nodeSheet.getRow(1); // System.out.println(row.getCell(0).toString()); // System.exit(0); JTextField uiHost = new JTextField("demo.brightcomputing.com"); // TextPrompt puiHost = new // TextPrompt("demo.brightcomputing.com",uiHost); JTextField uiUser = new JTextField("root"); // TextPrompt puiUser = new TextPrompt("root", uiUser); JTextField uiPass = new JPasswordField(""); // TextPrompt puiPass = new TextPrompt("x5deix5dei", uiPass); JPanel myPanel = new JPanel(new GridLayout(5, 1)); myPanel.add(new JLabel("Bright HeadNode hostname:")); myPanel.add(uiHost); // myPanel.add(Box.createHorizontalStrut(1)); // a spacer myPanel.add(new JLabel("Username:")); myPanel.add(uiUser); myPanel.add(new JLabel("Password:")); myPanel.add(uiPass); int result = JOptionPane.showConfirmDialog(null, myPanel, "Please fill in all the fields.", JOptionPane.OK_CANCEL_OPTION); if (result == JOptionPane.OK_OPTION) { System.out.println("Input received."); } String rhost = uiHost.getText(); String ruser = uiUser.getText(); String rpass = uiPass.getText(); String cmURL = "https://" + rhost + ":8081/json"; List<Cookie> cookies = doLogin(ruser, rpass, cmURL); chkVersion(cmURL, cookies); Map<String, Long> categories = UniqueKeyMap(cmURL, "cmdevice", "getCategories", cookies); Map<String, Long> networks = UniqueKeyMap(cmURL, "cmnet", "getNetworks", cookies); Map<String, Long> partitions = UniqueKeyMap(cmURL, "cmpart", "getPartitions", cookies); Map<String, Long> racks = UniqueKeyMap(cmURL, "cmpart", "getRacks", cookies); Map<String, Long> switches = UniqueKeyMap(cmURL, "cmdevice", "getEthernetSwitches", cookies); // System.out.println(switches.get("switch01")); // System.out.println("Size of the map: "+ switches.size()); // System.exit(0); cmDevice newnode = new cmDevice(); cmDevice.deviceObject devObj = new cmDevice.deviceObject(); cmDevice.switchObject switchObj = new cmDevice.switchObject(); // cmDevice.netObject netObj = new cmDevice.netObject(); List<String> emptyslist = new ArrayList<String>(); // Row nodeRow = nodeSheet.getRow(1); // Row ifRow = interfaceSheet.getRow(1); // System.out.println(nodeRow.getCell(0).toString()); // nodeRow.getCell(3).getStringCellValue() Map<String, ArrayList<cmDevice.netObject>> ifmap = new HashMap<String, ArrayList<cmDevice.netObject>>(); // Map<String,netObject> helperMap = new HashMap<String,netObject>(); // Iterator<Row> rows = interfaceSheet.rowIterator (); // while (rows. < interfaceSheet.getPhysicalNumberOfRows()) { // List<netObject> netList = new ArrayList<netObject>(); for (int i = 0; i < interfaceSheet.getPhysicalNumberOfRows(); i++) { Row ifRow = interfaceSheet.getRow(i); if (ifRow.getRowNum() == 0) { continue; // just skip the rows if row number is 0 } System.out.println("Row nr: " + ifRow.getRowNum()); cmDevice.netObject netObj = new cmDevice.netObject(); ArrayList<cmDevice.netObject> helperList = new ArrayList<cmDevice.netObject>(); netObj.setBaseType("NetworkInterface"); netObj.setCardType(ifRow.getCell(3).getStringCellValue()); netObj.setChildType(ifRow.getCell(4).getStringCellValue()); netObj.setDhcp((ifRow.getCell(5).getNumericCellValue() > 0.1) ? true : false); netObj.setIp(ifRow.getCell(7).getStringCellValue()); // netObj.setMac(ifRow.getCell(0).toString()); //netObj.setModified(true); netObj.setName(ifRow.getCell(1).getStringCellValue()); netObj.setNetwork(networks.get(ifRow.getCell(6).getStringCellValue())); //netObj.setOldLocalUniqueKey(0L); netObj.setRevision(""); netObj.setSpeed(ifRow.getCell(8, Row.CREATE_NULL_AS_BLANK).getStringCellValue()); netObj.setStartIf("ALWAYS"); netObj.setToBeRemoved(false); netObj.setUniqueKey((long) ifRow.getCell(2).getNumericCellValue()); //netObj.setAdditionalHostnames(new ArrayList<String>(Arrays.asList(ifRow.getCell(9, Row.CREATE_NULL_AS_BLANK).getStringCellValue().split("\\s*,\\s*")))); //netObj.setMac(ifRow.getCell(10, Row.CREATE_NULL_AS_BLANK).getStringCellValue()); netObj.setMode((int) ifRow.getCell(11, Row.CREATE_NULL_AS_BLANK).getNumericCellValue()); netObj.setOptions(ifRow.getCell(12, Row.CREATE_NULL_AS_BLANK).getStringCellValue()); netObj.setMembers(new ArrayList<String>(Arrays .asList(ifRow.getCell(13, Row.CREATE_NULL_AS_BLANK).getStringCellValue().split("\\s*,\\s*")))); // ifmap.put(ifRow.getCell(0).getStringCellValue(), new // HashMap<String, cmDevice.netObject>()); // helperMap.put(ifRow.getCell(1).getStringCellValue(), netObj) ; // ifmap.get(ifRow.getCell(0).getStringCellValue()).putIfAbsent(ifRow.getCell(1).getStringCellValue(), // netObj); // ifmap.put(ifRow.getCell(0).getStringCellValue(), helperMap); if (!ifmap.containsKey(ifRow.getCell(0).getStringCellValue())) { ifmap.put(ifRow.getCell(0).getStringCellValue(), new ArrayList<cmDevice.netObject>()); } helperList = ifmap.get(ifRow.getCell(0).getStringCellValue()); helperList.add(netObj); ifmap.put(ifRow.getCell(0).getStringCellValue(), helperList); continue; } for (int i = 0; i < nodeSheet.getPhysicalNumberOfRows(); i++) { Row nodeRow = nodeSheet.getRow(i); if (nodeRow.getRowNum() == 0) { continue; // just skip the rows if row number is 0 } newnode.setService("cmdevice"); newnode.setCall("addDevice"); Map<String, Long> ifmap2 = new HashMap<String, Long>(); for (cmDevice.netObject j : ifmap.get(nodeRow.getCell(0).getStringCellValue())) ifmap2.put(j.getName(), j.getUniqueKey()); switchObj.setEthernetSwitch(switches.get(nodeRow.getCell(8).getStringCellValue())); System.out.println(nodeRow.getCell(8).getStringCellValue()); System.out.println(switches.get(nodeRow.getCell(8).getStringCellValue())); switchObj.setPrt((int) nodeRow.getCell(9).getNumericCellValue()); switchObj.setBaseType("SwitchPort"); devObj.setBaseType("Device"); // devObj.setCreationTime(0L); devObj.setCustomPingScript(""); devObj.setCustomPingScriptArgument(""); devObj.setCustomPowerScript(""); devObj.setCustomPowerScriptArgument(""); devObj.setCustomRemoteConsoleScript(""); devObj.setCustomRemoteConsoleScriptArgument(""); devObj.setDisksetup(""); devObj.setBmcPowerResetDelay(0L); devObj.setBurning(false); devObj.setEthernetSwitch(switchObj); devObj.setExcludeListFull(""); devObj.setExcludeListGrab(""); devObj.setExcludeListGrabnew(""); devObj.setExcludeListManipulateScript(""); devObj.setExcludeListSync(""); devObj.setExcludeListUpdate(""); devObj.setFinalize(""); devObj.setRack(racks.get(nodeRow.getCell(10).getStringCellValue())); devObj.setRackHeight((long) nodeRow.getCell(11).getNumericCellValue()); devObj.setRackPosition((long) nodeRow.getCell(12).getNumericCellValue()); devObj.setIndexInsideContainer(0L); devObj.setInitialize(""); devObj.setInstallBootRecord(false); devObj.setInstallMode(""); devObj.setIoScheduler(""); devObj.setLastProvisioningNode(0L); devObj.setMac(nodeRow.getCell(6).getStringCellValue()); devObj.setModified(true); devObj.setCategory(categories.get(nodeRow.getCell(1).getStringCellValue())); devObj.setChildType("PhysicalNode"); //devObj.setDatanode((nodeRow.getCell(5).getNumericCellValue() > 0.1) ? true // : false); devObj.setHostname(nodeRow.getCell(0).getStringCellValue()); devObj.setModified(true); devObj.setPartition(partitions.get(nodeRow.getCell(2).getStringCellValue())); devObj.setUseExclusivelyFor("Category"); devObj.setNextBootInstallMode(""); devObj.setNotes(""); devObj.setOldLocalUniqueKey(0L); devObj.setPowerControl(nodeRow.getCell(7).getStringCellValue()); // System.out.println(ifmap.get("excelnode001").size()); // System.out.println(ifmap.get(nodeRow.getCell(0).getStringCellValue()).get(nodeRow.getCell(3).getStringCellValue()).getUniqueKey()); devObj.setManagementNetwork(networks.get(nodeRow.getCell(3).getStringCellValue())); devObj.setProvisioningNetwork(ifmap2.get(nodeRow.getCell(4).getStringCellValue())); devObj.setProvisioningTransport("RSYNCDAEMON"); devObj.setPxelabel(""); // "rack": 90194313218, // "rackHeight": 1, // "rackPosition": 4, devObj.setRaidconf(""); devObj.setRevision(""); devObj.setSoftwareImageProxy(null); devObj.setStartNewBurn(false); devObj.setTag("00000000a000"); devObj.setToBeRemoved(false); // devObj.setUcsInfoConfigured(null); // devObj.setUniqueKey(12345L); devObj.setUserdefined1(""); devObj.setUserdefined2(""); ArrayList<Object> mylist = new ArrayList<Object>(); ArrayList<cmDevice.netObject> mylist2 = new ArrayList<cmDevice.netObject>(); ArrayList<Object> emptylist = new ArrayList<Object>(); devObj.setFsexports(emptylist); devObj.setFsmounts(emptylist); devObj.setGpuSettings(emptylist); devObj.setFspartAssociations(emptylist); devObj.setPowerDistributionUnits(emptyslist); devObj.setRoles(emptylist); devObj.setServices(emptylist); devObj.setStaticRoutes(emptylist); mylist2 = ifmap.get(nodeRow.getCell(0).getStringCellValue()); devObj.setNetworks(mylist2); mylist.add(devObj); mylist.add(1); newnode.setArgs(mylist); GsonBuilder builder = new GsonBuilder(); builder.enableComplexMapKeySerialization(); // Gson g = new Gson(); Gson g = builder.create(); String json2 = g.toJson(newnode); // To be used from a real console and not Eclipse String message = JSonRequestor.doRequest(json2, cmURL, cookies); continue; } JOptionPane optionPaneF = new JOptionPane("The nodes have been added!"); JDialog myDialogF = optionPaneF.createDialog(null, "Complete: "); myDialogF.setModal(false); myDialogF.setVisible(true); doLogout(cmURL, cookies); // System.exit(0); }
From source file:com.camel.action.location.CityAction.java
public void handleFileUpload(FileUploadEvent event) { try {/* w ww . j av a 2 s. c o m*/ List<City> citiesList = new ArrayList<City>(); //Create the input stream from the xlsx/xls file String fileName = event.getFile().getFileName(); String cityCode = ""; String cityName = ""; String countryCode = ""; String countryName = ""; InputStream fis = event.getFile().getInputstream(); //Create Workbook instance for xlsx/xls file input stream Workbook workbook = null; if (fileName.toLowerCase().endsWith("xlsx")) { workbook = new XSSFWorkbook(fis); } else if (fileName.toLowerCase().endsWith("xls")) { workbook = new HSSFWorkbook(fis); } Sheet sheet = workbook.getSheetAt(0); Iterator<Row> rowIterator = sheet.iterator(); Row row = null; Iterator<Cell> cellIterator = null; Cell cell = null; City city = null; while (rowIterator.hasNext()) { cityCode = ""; cityName = ""; countryCode = ""; countryName = ""; row = rowIterator.next(); cellIterator = row.cellIterator(); if (row.getRowNum() == 0) continue; while (cellIterator.hasNext()) { cell = cellIterator.next(); switch (cell.getCellType()) { case Cell.CELL_TYPE_STRING: if (cityCode.equalsIgnoreCase("")) { cityCode = cell.getStringCellValue().trim(); } else if (cityName.equalsIgnoreCase("")) { cityName = cell.getStringCellValue().trim(); } else if (countryCode.equalsIgnoreCase("")) { countryCode = cell.getStringCellValue().trim(); } break; } } //end of cell iterator if (countryCode.equals("#N/A")) continue; country = findCountry(countryCode); if (country != null) { city = new City(); city.setCityCode(cityCode); city.setCityName(cityName); city.setCountry(country); citiesList.add(city); } } //end of rows iterator //close file input stream fis.close(); for (City c : citiesList) { super.setInstance(c); super.save(); } } catch (IOException e) { e.printStackTrace(); } FacesMessage message = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded."); FacesContext.getCurrentInstance().addMessage(null, message); country = null; }
From source file:com.camel.action.location.CountryAction.java
public void handleFileUpload(FileUploadEvent event) { String errorMessage = ""; try {// w w w. j av a 2s . c o m List<Country> countriesList = new ArrayList<Country>(); //Create the input stream from the xlsx/xls file String fileName = event.getFile().getFileName(); String name = ""; String shortCode = ""; String cont = ""; InputStream fis = event.getFile().getInputstream(); //Create Workbook instance for xlsx/xls file input stream Workbook workbook = null; if (fileName.toLowerCase().endsWith("xlsx")) { workbook = new XSSFWorkbook(fis); } else if (fileName.toLowerCase().endsWith("xls")) { workbook = new HSSFWorkbook(fis); } Sheet sheet = workbook.getSheetAt(0); Iterator<Row> rowIterator = sheet.iterator(); Row row = null; Iterator<Cell> cellIterator = null; Cell cell = null; Country country = null; while (rowIterator.hasNext()) { name = ""; shortCode = ""; cont = ""; row = rowIterator.next(); cellIterator = row.cellIterator(); if (row.getRowNum() == 0) { continue; } while (cellIterator.hasNext()) { cell = cellIterator.next(); switch (cell.getCellType()) { case Cell.CELL_TYPE_STRING: if (shortCode.equalsIgnoreCase("")) { shortCode = cell.getStringCellValue().trim(); } else if (name.equalsIgnoreCase("")) { name = cell.getStringCellValue().trim(); } else if (cont.equalsIgnoreCase("")) { cont = cell.getStringCellValue().trim(); } break; } } //end of cell iterator if (cont != null && cont.length() > 3) { country = new Country(); country.setContinet(Continent.valueOf(cont)); country.setCountryCode(shortCode); country.setCountryName(name); countriesList.add(country); } } //end of rows iterator fis.close(); for (Country c : countriesList) { super.setInstance(c); super.save(); } } catch (IOException e) { errorMessage = e.getMessage(); } System.out.println("eerrromessage..:" + errorMessage); FacesMessage message = null; if (errorMessage != null && errorMessage.length() > 3) { message = new FacesMessage("ERROR..:", "Country dosn't uploaded![" + errorMessage + "]"); } else { message = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded."); } FacesContext.getCurrentInstance().addMessage(null, message); }
From source file:com.camel.action.location.PortAction.java
public void handleFileUpload(FileUploadEvent event) { try {/* w w w. j av a 2s .co m*/ List<Port> portsList = new ArrayList<Port>(); //Create the input stream from the xlsx/xls file String fileName = event.getFile().getFileName(); String portCode = ""; String portName = ""; String cityCode = ""; String cityName = ""; String countryCode = ""; String countryName = ""; InputStream fis = event.getFile().getInputstream(); //Create Workbook instance for xlsx/xls file input stream Workbook workbook = null; if (fileName.toLowerCase().endsWith("xlsx")) { workbook = new XSSFWorkbook(fis); } else if (fileName.toLowerCase().endsWith("xls")) { workbook = new HSSFWorkbook(fis); } Sheet sheet = workbook.getSheetAt(0); Iterator<Row> rowIterator = sheet.iterator(); Row row = null; Iterator<Cell> cellIterator = null; Cell cell = null; City city = null; Port port = null; while (rowIterator.hasNext()) { portCode = ""; portName = ""; cityCode = ""; cityName = ""; countryCode = ""; countryName = ""; row = rowIterator.next(); cellIterator = row.cellIterator(); if (row.getRowNum() == 0) continue; while (cellIterator.hasNext()) { cell = cellIterator.next(); switch (cell.getCellType()) { case Cell.CELL_TYPE_STRING: if (portCode.equalsIgnoreCase("")) { portCode = cell.getStringCellValue().trim(); } else if (portName.equalsIgnoreCase("")) { portName = cell.getStringCellValue().trim(); } else if (cityCode.equalsIgnoreCase("")) { cityCode = cell.getStringCellValue().trim(); } else if (cityName.equalsIgnoreCase("")) { cityName = cell.getStringCellValue().trim(); } else if (countryCode.equalsIgnoreCase("")) { countryCode = cell.getStringCellValue().trim(); } else if (countryName.equalsIgnoreCase("")) { countryName = cell.getStringCellValue().trim(); } break; } } //end of cell iterator if (countryCode.equals("#N/A")) continue; country = findCountry(countryCode); city = findCity(cityCode); if (country != null && city != null) { port = new Port(); port.setPortType(PortType.SEAPORT); port.setPortCode(portCode); port.setPortName(portName); port.setCity(city); port.setCountry(country); portsList.add(port); } } //end of rows iterator //close file input stream fis.close(); for (Port c : portsList) { super.setInstance(c); super.save(); } } catch (IOException e) { e.printStackTrace(); } FacesMessage message = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded."); FacesContext.getCurrentInstance().addMessage(null, message); country = null; }