List of usage examples for org.apache.poi.hssf.usermodel HSSFSheet getLastRowNum
@Override public int getLastRowNum()
From source file:uk.ac.ebi.mnb.parser.ExcelXLSHelper.java
License:Open Source License
public String[][] getSheetData(HSSFSheet sheet) { int maxRow = sheet.getLastRowNum() + 1; int colNumber = INTIAL_COLUMN_NUMBER; String[][] data = new String[maxRow][colNumber]; List<String> block_xy1 = new ArrayList<String>(); List<String> block_xy2 = new ArrayList<String>(); int prevLastFilledColumn = -1; int emptyRows = 0; LOGGER.info("getting sheet data"); for (int i = 0; i < maxRow; i++) { HSSFRow row = sheet.getRow(i);/*ww w .j a v a 2 s.c o m*/ int lastFilledColumn = -1; if (row != null) { // convert to 1D array if (row.getLastCellNum() > 0) { String[] rowData = new String[row.getLastCellNum()]; for (int j = 0; j < row.getLastCellNum(); j++) { // check for empty rows HSSFCell cell = row.getCell(j); rowData[j] = getCellString(cell).trim(); if (rowData[j].isEmpty() == Boolean.FALSE) { lastFilledColumn = j; } } // resize if needed if (lastFilledColumn >= colNumber) { LOGGER.info("Sending resize row:" + i + " col:" + lastFilledColumn + " max:" + colNumber); data = resize(data, lastFilledColumn); colNumber = data[0].length; } // and copy the new data if (lastFilledColumn >= 0) { System.arraycopy(rowData, 0, data[i], 0, lastFilledColumn + 1); } } for (int j = row.getLastCellNum(); j < colNumber; j++) { if (j != -1) { data[i][j] = ""; } } if (lastFilledColumn == -1) { if (prevLastFilledColumn != -1) { // empty row block_xy2.add((i - 1) + "," + prevLastFilledColumn); } } else { if (block_xy2.size() == block_xy1.size()) { block_xy1.add(i + "," + 0); } } prevLastFilledColumn = lastFilledColumn; } emptyRows = lastFilledColumn <= 0 ? emptyRows + 1 : 0; if (emptyRows > 5) { return Arrays.copyOf(data, i - 5); } } for (int i = 0; i < block_xy2.size(); i++) { //System.out.println(block_xy1.get(i) + " to " + block_xy2.get(i)); } return data; }
From source file:utilidades.ExcelToXml.java
public void generateXML(File excelFile) { try { //Inicializamos el XML DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.newDocument(); Element rootElement = document.createElement("gasolineras"); document.appendChild(rootElement); //Creamos el elemento principal InputStream input = new FileInputStream(excelFile); HSSFWorkbook workbook = new HSSFWorkbook(input); HSSFSheet spreadsheet = workbook.getSheetAt(0); for (int i = 5; i <= spreadsheet.getLastRowNum(); i++) { Element stmtElement1 = document.createElement("gasolinera"); rootElement.appendChild(stmtElement1); Attr attr = document.createAttribute("id"); attr.setValue(Integer.toString(i - 4)); stmtElement1.setAttributeNode(attr); HSSFRow filaActiva = spreadsheet.getRow(i); //Aadiendo los elementos Element rotulo = document.createElement("rotulo"); stmtElement1.appendChild(rotulo); rotulo.appendChild(document.createTextNode(filaActiva.getCell(18).getStringCellValue())); Element provincia = document.createElement("provincia"); stmtElement1.appendChild(provincia); provincia.appendChild(document.createTextNode(filaActiva.getCell(0).getStringCellValue())); Element localidad = document.createElement("localidad"); stmtElement1.appendChild(localidad); localidad.appendChild(document.createTextNode(filaActiva.getCell(3).getStringCellValue())); Element cp = document.createElement("codigoPostal"); stmtElement1.appendChild(cp); cp.appendChild(document.createTextNode(filaActiva.getCell(4).getStringCellValue())); Element direccion = document.createElement("direccion"); stmtElement1.appendChild(direccion); direccion.appendChild(document.createTextNode(filaActiva.getCell(5).getStringCellValue())); Element gasolinas = document.createElement("combustibles"); stmtElement1.appendChild(gasolinas); Element gasolina95 = document.createElement("Gasolina95"); gasolinas.appendChild(gasolina95); gasolina95.appendChild(document.createTextNode(filaActiva.getCell(9).getStringCellValue())); Element gasoleo = document.createElement("gasoleo"); gasolinas.appendChild(gasoleo); gasoleo.appendChild(document.createTextNode(filaActiva.getCell(10).getStringCellValue())); Element horario = document.createElement("horario"); stmtElement1.appendChild(horario); horario.appendChild(document.createTextNode(filaActiva.getCell(21).getStringCellValue())); }// ww w . jav a 2 s . co m TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); //Add indentation to output transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); DOMSource source = new DOMSource(document); StreamResult result = new StreamResult(new File("gasolineras.xml")); transformer.transform(source, result); } catch (IOException e) { System.out.println("IOException " + e.getMessage()); } catch (ParserConfigurationException e) { System.out.println("ParserConfigurationException " + e.getMessage()); } catch (TransformerConfigurationException e) { System.out.println("TransformerConfigurationException " + e.getMessage()); } catch (TransformerException e) { System.out.println("TransformerException " + e.getMessage()); } }
From source file:utilitario.Excel_Reader.java
public String leer_excel(FileInputStream archivo_entrada, int tipo_asistencia) { String resultado = ""; try {//from ww w . j a v a2 s.c o m POIFSFileSystem fs = new POIFSFileSystem(archivo_entrada); HSSFWorkbook wb = new HSSFWorkbook(fs); HSSFSheet sheet = wb.getSheetAt(0); Row row; if (tipo_asistencia == 1) { //ArrayList<Detalle_Padron_Asistencia> listdetpadasis=new ArrayList<Detalle_Padron_Asistencia>(); for (int i = 0; i <= sheet.getLastRowNum(); i++) { row = sheet.getRow(i); //int num_emp = (int) row.getCell(0).getNumericCellValue(); //Detalle_Padron_Asistencia d=new Detalle_Padron_Asistencia(); String nombre = row.getCell(2).getStringCellValue(); String horario = row.getCell(3).getStringCellValue(); String estado = row.getCell(6).getStringCellValue(); String valor_estado = ""; if (estado.equalsIgnoreCase("Registro normal")) { valor_estado = "A"; //d.setVar_estado(valor_estado); } if (estado.equalsIgnoreCase("Invalido")) { valor_estado = "T"; //d.setVar_estado(valor_estado); } String dni = ""; if (i == 0) { dni = String.valueOf(row.getCell(0).getStringCellValue()); } else { dni = String.valueOf(row.getCell(0).getNumericCellValue()).substring(0, 9).replace(".", ""); //d.setVar_dni(dni); //listdetpadasis.add(d); } //Evaluar dentro de la base de datos los que no asistieron y generar multa resultado = resultado + dni + " | " + nombre + " | " + horario + " | " + estado + "\n"; } /*BLPadron_Asistencia p=new BLPadron_Asistencia(); boolean result=false; result=p.Registrar_PadronAsistencia(listdetpadasis, 1); if(result==true){ JOptionPane.showMessageDialog(null, "Registro Correcto"); }*/ } else { //ArrayList<Detalle_Padron_Asistencia> listdetpadasis=new ArrayList<Detalle_Padron_Asistencia>(); for (int i = 0; i <= sheet.getLastRowNum(); i++) { row = sheet.getRow(i); //int num_emp = (int) row.getCell(0).getNumericCellValue(); //Detalle_Padron_Asistencia d=new Detalle_Padron_Asistencia(); String nombre = row.getCell(2).getStringCellValue(); String horario = row.getCell(3).getStringCellValue(); String estado = row.getCell(6).getStringCellValue(); String valor_estado = ""; if (estado.equalsIgnoreCase("Registro normal")) { valor_estado = "A"; //d.setVar_estado(valor_estado); } if (estado.equalsIgnoreCase("Invalido")) { valor_estado = "T"; //d.setVar_estado(valor_estado); } String dni = ""; if (i == 0) { dni = String.valueOf(row.getCell(0).getStringCellValue()); } else { dni = String.valueOf(row.getCell(0).getNumericCellValue()).substring(0, 9).replace(".", ""); //d.setVar_dni(dni); //listdetpadasis.add(d); } //Evaluar dentro de la base de datos los que no asistieron y generar multa resultado = resultado + dni + " | " + nombre + " | " + horario + " | " + estado + "\n"; } /*BLPadron_Asistencia p=new BLPadron_Asistencia(); boolean result=false; result=p.Registrar_PadronAsistencia(listdetpadasis, 1); if(result==true){ JOptionPane.showMessageDialog(null, "Registro Correcto"); }*/ } archivo_entrada.close(); } catch (IOException ioe) { System.out.println(ioe); } return resultado; }
From source file:utilitario.Excel_Reader.java
public String leer_registrar_excel(FileInputStream archivo_entrada, int tipo_asistencia) { String resultado = ""; try {// ww w . j a v a 2 s .c om POIFSFileSystem fs = new POIFSFileSystem(archivo_entrada); HSSFWorkbook wb = new HSSFWorkbook(fs); HSSFSheet sheet = wb.getSheetAt(0); Row row; if (tipo_asistencia == 1) { ArrayList<Detalle_Padron_Asistencia> listdetpadasis = new ArrayList<Detalle_Padron_Asistencia>(); for (int i = 0; i <= sheet.getLastRowNum(); i++) { row = sheet.getRow(i); //int num_emp = (int) row.getCell(0).getNumericCellValue(); Detalle_Padron_Asistencia d = new Detalle_Padron_Asistencia(); String nombre = row.getCell(2).getStringCellValue(); String horario = row.getCell(3).getStringCellValue(); String estado = row.getCell(6).getStringCellValue(); String valor_estado = ""; if (estado.equalsIgnoreCase("Registro normal") || estado.equalsIgnoreCase("Invalido")) { valor_estado = "A"; d.setVar_estado(valor_estado); } String dni = ""; if (i == 0) { dni = String.valueOf(row.getCell(0).getStringCellValue()); } else { dni = String.valueOf(row.getCell(0).getNumericCellValue()).substring(0, 9).replace(".", ""); d.setVar_dni(dni); listdetpadasis.add(d); } //Evaluar dentro de la base de datos los que no asistieron y generar multa resultado = resultado + dni + " | " + nombre + " | " + horario + " | " + estado + "\n"; } BLPadron_Asistencia p = new BLPadron_Asistencia(); boolean result = false; result = p.Registrar_PadronAsistencia(listdetpadasis, 1); if (result == true) { JOptionPane.showMessageDialog(null, "Registro Correcto"); } } else { ArrayList<Detalle_Padron_Asistencia> listdetpadasis = new ArrayList<Detalle_Padron_Asistencia>(); for (int i = 0; i <= sheet.getLastRowNum(); i++) { row = sheet.getRow(i); //int num_emp = (int) row.getCell(0).getNumericCellValue(); Detalle_Padron_Asistencia d = new Detalle_Padron_Asistencia(); String nombre = row.getCell(2).getStringCellValue(); String horario = row.getCell(3).getStringCellValue(); String estado = row.getCell(6).getStringCellValue(); String valor_estado = ""; if (estado.equalsIgnoreCase("Registro normal") || estado.equalsIgnoreCase("Invalido")) { valor_estado = "A"; d.setVar_estado(valor_estado); } String dni = ""; if (i == 0) { dni = String.valueOf(row.getCell(0).getStringCellValue()); } else { dni = String.valueOf(row.getCell(0).getNumericCellValue()).substring(0, 9).replace(".", ""); d.setVar_dni(dni); listdetpadasis.add(d); } //Evaluar dentro de la base de datos los que no asistieron y generar multa resultado = resultado + dni + " | " + nombre + " | " + horario + " | " + estado + "\n"; } BLPadron_Asistencia p = new BLPadron_Asistencia(); boolean result = false; result = p.Registrar_PadronAsistencia(listdetpadasis, 1); if (result == true) { JOptionPane.showMessageDialog(null, "Registro Correcto"); } } archivo_entrada.close(); } catch (IOException ioe) { System.out.println(ioe); } return resultado; }
From source file:velo.importer.AccountsList.java
License:Open Source License
public void importFromXls(InputStream is, String spreadSheetName) throws Exception { HSSFWorkbook workbook = new HSSFWorkbook(is); //Count the number of sheets if (workbook.getNumberOfSheets() < 1) { throw new Exception("Number of sheets in excel is less than 1!"); }//from www .j av a2 s .com HSSFSheet sheet = workbook.getSheet(spreadSheetName); if (sheet == null) { throw new Exception("Could not find sheet named '" + spreadSheetName + "'"); } //todo 3 cells at least! //Make sure the headers correspond to the expected values HSSFRow header = sheet.getRow(0); HSSFCell accountNameTitle = header.getCell((short) 0); HSSFCell targetNameTitle = header.getCell((short) 1); if (!accountNameTitle.toString().equalsIgnoreCase("ACCOUNT")) { throw new Exception( "Column one in first row must equal to 'ACCOUNT' and represents the Account to associate"); } if (!targetNameTitle.toString().equalsIgnoreCase("RESOURCE_UNIQUE_NAME")) { throw new Exception( "Column one in first row must equal to 'RESOURCE_UNIQUE_NAME' and represents the resource unique name the account is related to!"); } for (int i = 1; i <= sheet.getLastRowNum(); i++) { HSSFRow row = sheet.getRow(i); HSSFCell accountName = row.getCell((short) 0); HSSFCell targetName = row.getCell((short) 1); String targetNameErrMsg = "Target Name at row # '" + i + "' is empty!"; if (targetName == null) { throw new Exception(targetNameErrMsg); } else if (targetName.toString().length() < 1) { throw new Exception(targetNameErrMsg); } String accountErrMsg = "Account Name at row # '" + i + "' is empty!"; if (accountName == null) { throw new Exception(accountErrMsg); } else if (accountName.toString().length() < 1) { throw new Exception(accountErrMsg); } System.out.println("Row(" + i + ") - Account: '" + accountName.toString() + "', On Target: '" + targetName.toString() + "'"); velo.importer.ImportAccount ia = new velo.importer.ImportAccount(); ia.setResourceName(targetName.toString()); ia.setAccountName(accountName.toString()); this.add(ia); } }
From source file:velo.importer.AccountsToUsersList.java
License:Open Source License
public void importFromXls(InputStream is, String spreadSheetName) throws Exception { HSSFWorkbook workbook = new HSSFWorkbook(is); //Count the number of shits if (workbook.getNumberOfSheets() < 1) { throw new Exception("Number of sheets in excel is less than 1!"); }//from www . j a v a 2 s. c om HSSFSheet sheet = workbook.getSheet(spreadSheetName); if (sheet == null) { throw new Exception("Could not find sheet named '" + spreadSheetName + "'"); } //todo 3 cells at least! //Make sure the headers correspond to the expected values HSSFRow header = sheet.getRow(0); HSSFCell userNameTitle = header.getCell((short) 0); HSSFCell accountNameTitle = header.getCell((short) 1); HSSFCell targetNameTitle = header.getCell((short) 2); if (!userNameTitle.toString().equalsIgnoreCase("USER")) { throw new Exception( "Column one in first row must equal to 'USER' and represents the User that owns the account!"); } if (!accountNameTitle.toString().equalsIgnoreCase("ACCOUNT")) { throw new Exception( "Column one in first row must equal to 'ACCOUNT' and represents the Account to associate"); } if (!targetNameTitle.toString().equalsIgnoreCase("RESOURCE_UNIQUE_NAME")) { throw new Exception( "Column one in first row must equal to 'TARGET-SYSTEM' and represents the resource unique name the account is related to!"); } for (int i = 1; i <= sheet.getLastRowNum(); i++) { HSSFRow row = sheet.getRow(i); HSSFCell userName = row.getCell((short) 0); HSSFCell accountName = row.getCell((short) 1); HSSFCell targetName = row.getCell((short) 2); String targetNameErrMsg = "Target Name at row # '" + i + "' is empty!"; if (targetName == null) { throw new Exception(targetNameErrMsg); } else if (targetName.toString().length() < 1) { throw new Exception(targetNameErrMsg); } String userNameErrMsg = "User Name at row # '" + i + "' is empty!"; if (userName == null) { throw new Exception(userNameErrMsg); } else if (userName.toString().length() < 1) { throw new Exception(userNameErrMsg); } String accountErrMsg = "Account Name at row # '" + i + "' is empty!"; if (accountName == null) { throw new Exception(accountErrMsg); } else if (accountName.toString().length() < 1) { throw new Exception(accountErrMsg); } //System.out.println("Row("+i+") - User: '" + userName.toString() + "', Account: '" + accountName.toString() + "', On Target: '" + targetName.toString() + "'"); velo.importer.ImportAccountToUser iatu = new velo.importer.ImportAccountToUser(); iatu.setUserName(userName.toString()); iatu.setResourceName(targetName.toString()); iatu.setAccountName(accountName.toString()); this.add(iatu); } }
From source file:velo.importer.RolesToRolesFolderList.java
License:Open Source License
public void importFromXls(InputStream is, String spreadSheetName) throws Exception { HSSFWorkbook workbook = new HSSFWorkbook(is); //Count the number of sheets if (workbook.getNumberOfSheets() < 1) { throw new Exception("Number of sheets in excel is less than 1!"); }/*w w w . j a va2s. co m*/ HSSFSheet sheet = workbook.getSheet(spreadSheetName); if (sheet == null) { throw new Exception("Could not find sheet named '" + spreadSheetName + "'"); } //todo 3 cells at least! //Make sure the headers correspond to the expected values HSSFRow header = sheet.getRow(0); HSSFCell accountNameTitle = header.getCell((short) 0); HSSFCell targetNameTitle = header.getCell((short) 1); if (!accountNameTitle.toString().equalsIgnoreCase("ROLE_UNIQUE_NAME")) { throw new Exception( "Column one in first row must equal to 'ROLE_UNIQUE_NAME' and represents the Role to create"); } if (!targetNameTitle.toString().equalsIgnoreCase("ROLES_FOLDER_UNIQUE_NAME")) { throw new Exception( "Column one in first row must equal to 'ROLES_FOLDER_UNIQUE_NAME' and represents the roles folder unique name the role is related to!"); } for (int i = 1; i <= sheet.getLastRowNum(); i++) { HSSFRow row = sheet.getRow(i); HSSFCell roleName = row.getCell((short) 0); HSSFCell rolesFolderName = row.getCell((short) 1); String RolesFolderNameErrMsg = "Roles Folder Name at row # '" + i + "' is empty!"; if (rolesFolderName == null) { throw new Exception(RolesFolderNameErrMsg); } else if (rolesFolderName.toString().length() < 1) { throw new Exception(RolesFolderNameErrMsg); } String roleErrMsg = "Role Name at row # '" + i + "' is empty!"; if (roleName == null) { throw new Exception(roleErrMsg); } else if (roleName.toString().length() < 1) { throw new Exception(roleErrMsg); } System.out.println("Row(" + i + ") - Role: '" + roleName.toString() + "', On Roles Folder: '" + rolesFolderName.toString() + "'"); ImportRoleToRolesFolder role = new ImportRoleToRolesFolder(roleName.toString(), rolesFolderName.toString()); this.add(role); } }
From source file:ypcnv.views.impl.FileXLS.java
License:Open Source License
/** * Read data row by row and put it into model. * /*w w w. j ava2s. c om*/ * @param headerRow * - row previous to row with real data, in fact this is row with * columns headers. * @throws ContactException */ private void insertDataToModel(HSSFRow headerRow) { HSSFSheet currentSheet = headerRow.getSheet(); int lastRowIdx = currentSheet.getLastRowNum(); int currentRowIdx = headerRow.getRowNum() + 1; for (; currentRowIdx <= lastRowIdx; currentRowIdx++) { Contact2k3 currentContact = new Contact2k3(); Boolean isVoidContact = true; for (String dataFieldKeyName : currentContact.getFieldValuesMap().keySet()) { int cellIdx = dataColumnsSequenceMap.get(dataFieldKeyName); HSSFCell cell = currentSheet.getRow(currentRowIdx).getCell(cellIdx, Row.RETURN_BLANK_AS_NULL); String cellValue = null; if (cell != null) { cellValue = getCellContent(cell); } else { cellValue = ""; } if (!cellValue.equals("")) { isVoidContact = false; } try { currentContact.setValue(dataFieldKeyName, cellValue); } catch (ContactException e) { LOG.error(String.format(FileXLSMeta.ERR_MESSAGE_NO_KEY_IN_MAP, dataFieldKeyName)); e.printStackTrace(); } } if (!isVoidContact) { dataContainer.add(currentContact); } } }
From source file:ypcnv.views.impl.FileXLS.java
License:Open Source License
/** * Insert data from model into workbook object instance. * //from w ww.j a v a2s.co m * @param headerRow * - row previous to row with real data, in fact this is row with * columns headers. */ private void insertDataToWorkbook(HSSFRow headerRow) { Contact2k3 currentContact; Iterator<Contact2k3> containerModelListIterator = dataContainer.getContacts().iterator(); HSSFSheet currentSheet = headerRow.getSheet(); HSSFRow currentRow; HSSFCell currentCell; int currentRowIdx = headerRow.getRowNum() + 1; int lastRowIdx = currentSheet.getLastRowNum(); int currentColumnIdx; // XXX - there is silent wipe of previous content of the sheet. for (int idx = currentRowIdx; idx <= lastRowIdx; idx++) { currentSheet.removeRow(currentSheet.getRow(idx)); } for (; containerModelListIterator.hasNext(); currentRowIdx++) { currentContact = containerModelListIterator.next(); currentSheet.createRow(currentRowIdx); currentRow = currentSheet.getRow(currentRowIdx); for (String dataFieldKeyName : dataColumnsSequenceMap.keySet()) { currentColumnIdx = dataColumnsSequenceMap.get(dataFieldKeyName); currentRow.createCell(currentColumnIdx); currentCell = currentRow.getCell(currentColumnIdx); currentCell.setCellType(Cell.CELL_TYPE_STRING); currentCell.setCellValue(currentContact.getFieldValuesMap().get(dataFieldKeyName)); } } }