List of usage examples for org.apache.poi.hssf.usermodel HSSFSheet getLastRowNum
@Override public int getLastRowNum()
From source file:gov.nih.nci.cabig.caaers.dataimport.AgentSpecificTermsImporter.java
License:BSD License
public Map<String, Object> importFile() throws Exception { POIFSFileSystem poifs;/*from w ww .j a v a2s. c om*/ HSSFWorkbook wb; HSSFSheet sh = null; boolean isExcel = file.getName().endsWith(".xls"); boolean isCSV = file.getName().endsWith(".csv"); Map<String, Object> results = new HashMap<String, Object>(); int rowCount = 0; int columnsCount = 0; Map<String, Agent> agents = new HashMap<String, Agent>(); Map<String, Agent> missingAgents = new HashMap<String, Agent>(); Set<String> missingTerms = new HashSet<String>(); Map<String, String> asaelCache = new HashMap<String, String>(); int asael; // wipe out the table agentSpecificTermDao.deleteAll(); studyDao.deleteAllExpectedTerms(); // if (true) return null; // get needed headers if (isExcel) { poifs = new POIFSFileSystem(new FileInputStream(file)); wb = new HSSFWorkbook(poifs); sh = wb.getSheetAt(0); rowCount = sh.getLastRowNum(); columnsCount = sh.getRow(0).getLastCellNum(); for (byte i = 0; i < columnsCount; i++) { HSSFCell cell = sh.getRow(0).getCell(i); if (headers.containsKey(cell.getStringCellValue())) { headers.remove(cell.getStringCellValue()); headers.put(cell.getStringCellValue(), Short.valueOf(i)); } } } InputStream ir = null; Reader r = null; BufferedReader br = null; if (isCSV) { // readLines rowCount = 0; ir = new FileInputStream(file); r = new InputStreamReader(ir); br = new BufferedReader(r); String s = br.readLine(); while (s != null) { if (rowCount == 0) { String[] _s = s.split("[\\|]{1}"); for (byte j = 0; j < _s.length; j++) { // System.out.println(_s[j]); if (headers.containsKey(_s[j])) { headers.remove(_s[j]); headers.put(_s[j], Short.valueOf(j)); } } } rowCount++; s = br.readLine(); } br.close(); r.close(); ir.close(); ir = new FileInputStream(file); r = new InputStreamReader(ir); br = new BufferedReader(r); } /* System.out.println(rowCount); for (Map.Entry e : headers.entrySet()) { System.out.println(e.getKey() + "=>" + e.getValue()); } */ agents.clear(); missingTerms.clear(); missingAgents.clear(); asael = 0; int duplicateAgentTerms = 0; // String nsc = ""; String ctcae_category = ""; String ctcae_version = "0.0"; String ae_term = ""; String other_toxicity = ""; // Loading ASAE list // if (true) { return null; } int i = 1; while (i <= rowCount) { nsc = ""; if (isExcel) { HSSFRow row = sh.getRow(i); if (row != null) { nsc = getCellData("", i, row.getCell((short) headers.get("NSC"))); ctcae_category = getCellData("", i, row.getCell((short) headers.get("CTCAE_CATEGORY"))); ctcae_version = getCellData("", i, row.getCell((short) headers.get("CTCAE_VERSION"))); ae_term = getCellData("", i, row.getCell((short) headers.get("AE_TERM"))); other_toxicity = getCellData("", i, row.getCell((short) headers.get("OTHER_TOXICITY"))); } } else { String s; s = br.readLine(); if (s != null) { String[] _s = s.split("[\\|]{1}"); if (i > 1 && _s.length > 1) { nsc = _s[headers.get("NSC")]; ctcae_category = _s[headers.get("CTCAE_CATEGORY")]; try { ctcae_version = _s[headers.get("CTCAE_VERSION")].trim(); } catch (NumberFormatException e) { // System.out.println(s); return null; } ae_term = _s[headers.get("AE_TERM")]; if (_s.length - 1 >= headers.get("OTHER_TOXICITY")) other_toxicity = _s[headers.get("OTHER_TOXICITY")]; else other_toxicity = ""; } } } if (nsc.trim().equals("")) { i++; continue; } else { // System.out.println(String.format("%s). NSC:%s, V:%s, C:%s, T:%s", i, nsc, ctcae_version, ctcae_category, ae_term)); } Agent a = agents.get(nsc); if (a == null) { a = agentDao.getByNscNumber(nsc); // System.out.println(asael + ". OK. Found agent [" + a.getName() + "] for NSC: [" + nsc + "]"); agents.put(nsc, a); } if (a != null) { AgentSpecificCtcTerm t = new AgentSpecificCtcTerm(); t.setAgent(a); t.setOtherToxicity(other_toxicity); List<CtcTerm> list = terminologyRepository.getCtcTerm(ctcae_category, ctcae_version, ae_term); if (list.size() == 0) { // System.out.println("<ERROR>: Term not found: " + ae_term + ", Category: " + ctcae_category + ", CTCAE Version: " + ctcae_version); missingTerms.add("Term not found: " + ae_term + ", Category: " + ctcae_category + ", CTCAE Version: " + ctcae_version); } else { t.setCtcTerm(list.get(0)); if (persistASAE(t)) asael++; else duplicateAgentTerms++; } agentSpecificTermDao.evict(t); } else { if (!missingAgents.containsKey(nsc)) { // System.out.println("<ERROR>: The agent was not found by its NSC: " + nsc); missingAgents.put(nsc, null); } } i++; } if (isCSV) { br.close(); r.close(); ir.close(); } results.put(KEY_MISSING_TERMS, missingTerms); results.put(KEY_PROCESSED_AGENTS, agents.size() - missingAgents.size()); results.put(KEY_PROCESSED_AGENTTERMS, asael); results.put(KEY_MISSING_AGENTS, missingAgents); results.put(KEY_DUPLICATE_AGENT_TERMS, duplicateAgentTerms); return results; }
From source file:gov.nih.nci.evs.browser.utils.ExcelUtil.java
License:Open Source License
public static int getHSSFEndRow(String file, int sheet, int col, String code) { int num = -1; try {/* w ww. j ava 2 s . c om*/ FileInputStream fis = new FileInputStream(new File(file)); //Get the workbook instance for XLS file HSSFWorkbook workbook = new HSSFWorkbook(fis); try { fis.close(); } catch (Exception ex) { ex.printStackTrace(); } //Get first sheet from the workbook HSSFSheet hSSFSheet = workbook.getSheetAt(sheet); if (col == -1) { return hSSFSheet.getLastRowNum(); } //Get iterator to all the rows in current sheet Iterator<Row> rowIterator = hSSFSheet.iterator(); //Get iterator to all cells of current row int lcv = 0; while (rowIterator.hasNext()) { Row row = rowIterator.next(); if (row == null) return -1; //if (row.getCell(0).getStringCellValue().compareTo(code) == 0 || if (row.getCell(col).getStringCellValue().compareTo(code) == 0) { num = lcv; } lcv++; } } catch (Exception ex) { ex.printStackTrace(); } return num; }
From source file:gtu._work.etc.TestCaseExcelMakerUI.java
License:Open Source License
void loadInitExcel() throws Exception { File file = new File("C:/Users/gtu001/Desktop/RL-10?.xls"); HSSFWorkbook book = ExcelUtil.getInstance().readExcel(file); Map<String, String> map = new HashMap<String, String>(); for (int ii = 0; ii < book.getNumberOfSheets(); ii++) { HSSFSheet sheet = book.getSheetAt(ii); for (int jj = 0; jj <= sheet.getLastRowNum(); jj++) { if (sheet.getRow(jj).getCell(0) == null) { continue; }// w w w. jav a 2 s . c om if (sheet.getRow(jj).getCell(1) == null) { continue; } String key = ExcelUtil.getInstance().readHSSFCell(sheet.getRow(jj).getCell(0)).toUpperCase();//title num String value = ExcelUtil.getInstance().readHSSFCell(sheet.getRow(jj).getCell(1));//title chn map.put(key, value); } } File dir = new File("C:/Users/gtu001/Desktop/ (2)"); Set<String> list = new HashSet<String>(); for (File f : dir.listFiles()) { list.add(f.getName().replaceAll("\\.jpg", "").replaceAll("[a-zA-Z]$", "").toUpperCase()); } JTableUtil util = JTableUtil.newInstance(jTable1); StringBuilder sb = new StringBuilder(); for (Iterator<String> it = list.iterator(); it.hasNext();) { String key = it.next(); if (map.containsKey(key)) { util.getModel().addRow(new Object[] { "rl" + key, map.get(key), "", "" }); } else { sb.append(key + "\n"); } } if (sb.length() != 0) { JCommonUtil._jOptionPane_showMessageDialog_error(sb.toString()); } }
From source file:guardias.CalendarioExcel.java
private void leerExcelFile(File excelFile, List<Medico> listadoMedicos) { InputStream excelStream = null; try {//from w ww . ja va2 s. c om excelStream = new FileInputStream(excelFile); // Representacin del ms alto nivel de la hoja excel. HSSFWorkbook hssfWorkbook = new HSSFWorkbook(excelStream); // Elegimos la hoja que se pasa por parmetro. HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(0); // Objeto que nos permite leer un fila de la hoja excel, y de aqu extraer el contenido de las celdas. HSSFRow hssfRow; // Obtengo el nmero de filas ocupadas en la hoja int rows = hssfSheet.getLastRowNum(); // Cadena que usamos para almacenar la lectura de la celda Date cellCalendario; String cellFestivo; String cellPeticion; this.leerGuardiasPrevistas(hssfSheet.getRow(FILA_DEFINICION_GUARDIAS_PREVISTAS), listadoMedicos); List<DiaCalendario> listadoDias = new ArrayList<>(); // Para este ejemplo vamos a recorrer las filas obteniendo los datos que queremos for (int r = COMIENZO_FILAS; r < rows; r++) { hssfRow = hssfSheet.getRow(r); if (hssfRow == null) { break; } else { cellCalendario = hssfRow.getCell(COLUMNA_FECHA_MES).getDateCellValue(); if (cellCalendario != null) { cellFestivo = hssfRow.getCell(COLUMNA_FESTIVO) == null ? "" : hssfRow.getCell(COLUMNA_FESTIVO).getStringCellValue(); LOGGER.log(Level.FINE, "Row: {0} -> [Columna {1}: {2}] [Columna {3}: {4}] ", new Object[] { r, COLUMNA_FECHA_MES, cellFestivo, COLUMNA_FESTIVO, cellFestivo }); DiaCalendario diaCalendario = new DiaCalendario(); diaCalendario.setTime(cellCalendario.getTime()); //Se comprueba si es sabado o Domingo if (TratarFechas.esFinde(diaCalendario)) { diaCalendario.setEsFinde(Boolean.TRUE); //TODO setear nivel de importancia (cada dia del finde tiene una importancia) } else { diaCalendario.setEsFinde(Boolean.FALSE); } if (ES_FESTIVO.equalsIgnoreCase(cellFestivo)) { //Por norma general los festivos se pondrn a dedo diaCalendario.setEsFestivo(Boolean.TRUE); } else { diaCalendario.setEsFestivo(Boolean.FALSE); } //No se tiene en cuenta que tipo de falta tiene (solo tiene que estar vacio) this.obtenerDisponibilidadMedicosEnExcel(listadoMedicos, hssfRow, diaCalendario, listadoMedicos); cellPeticion = hssfRow.getCell(COLUMNA_PETICION) == null ? "" : hssfRow.getCell(COLUMNA_PETICION).getStringCellValue(); LOGGER.log(Level.FINE, "----{0}", cellPeticion); diaCalendario.setPeticionMedico(cellPeticion); listadoDias.add(diaCalendario); } } } this.setListadoDiasCalendario(listadoDias); } catch (FileNotFoundException fileNotFoundException) { LOGGER.log(Level.WARNING, "The file not exists (No se encontro el fichero): {0}", fileNotFoundException); } catch (IOException ex) { LOGGER.log(Level.WARNING, "Error in file procesing (Error al procesar el fichero): {0}", ex); } catch (ExceptionColumnaDisponibilidad ex) { LOGGER.log(Level.WARNING, "Error en lectura de celdas al leer la dispoibilidad, hay alguna celda que no es ni " + CONSTANTE_FIESTA + " ni " + CONSTANTE_CONSULTA + "{0}", ex); } finally { try { excelStream.close(); } catch (IOException ex) { LOGGER.log(Level.WARNING, "Error in file processing after close it (Error al procesar el fichero despues de cerrarlo): {0}", ex); } } }
From source file:Import.Utils.XSSFConvert.java
/** * @param destination the sheet to create from the copy. * @param the sheet to copy.//w ww . ja v a 2 s . c o m * @param copyStyle true copy the style. */ public static void copySheets(HSSFSheet source, XSSFSheet destination, boolean copyStyle) { int maxColumnNum = 0; Map<Integer, HSSFCellStyle> styleMap = (copyStyle) ? new HashMap<Integer, HSSFCellStyle>() : null; for (int i = source.getFirstRowNum(); i <= source.getLastRowNum(); i++) { HSSFRow srcRow = source.getRow(i); XSSFRow destRow = destination.createRow(i); if (srcRow != null) { copyRow(source, destination, srcRow, destRow, styleMap); if (srcRow.getLastCellNum() > maxColumnNum) { maxColumnNum = srcRow.getLastCellNum(); } } } for (int i = 0; i <= maxColumnNum; i++) { destination.setColumnWidth(i, source.getColumnWidth(i)); } }
From source file:is.idega.idegaweb.egov.fsk.business.FSKBusinessBean.java
License:Open Source License
@Override public Map importExcelFile(UploadFile file, Object coursePK, int column) { Map map = new HashMap(); try {// w ww. jav a2 s . c o m Course course = getCourse(coursePK); Group group = course.getGroup(); FileInputStream input = new FileInputStream(file.getRealPath()); HSSFWorkbook wb = new HSSFWorkbook(input); HSSFSheet sheet = wb.getSheetAt(0); NumberFormat format = NumberFormat.getNumberInstance(); format.setGroupingUsed(false); format.setMinimumIntegerDigits(10); Collection imported = new ArrayList(); Collection alreadyImported = new ArrayList(); Collection outsideCommune = new ArrayList(); Collection outsideAgeRange = new ArrayList(); Collection invalidPersonalID = new ArrayList(); Collection noUserFound = new ArrayList(); for (int a = sheet.getFirstRowNum(); a <= sheet.getLastRowNum(); a++) { HSSFRow row = sheet.getRow(a); HSSFCell cell = row.getCell((short) (column - 1)); if (cell == null) { continue; } String personalID = null; if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) { personalID = cell.getStringCellValue(); } else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) { personalID = String.valueOf(new Double(cell.getNumericCellValue()).longValue()); } else { personalID = cell.getStringCellValue(); } try { personalID = format.format(format.parse(personalID.replaceAll("-", ""))); } catch (ParseException e1) { e1.printStackTrace(); continue; } if (SocialSecurityNumber.isValidSocialSecurityNumber(personalID, getDefaultLocale())) { try { User user = getUserBusiness().getUser(personalID); if (!group.hasRelationTo(((Integer) user.getPrimaryKey()).intValue())) { IWTimestamp dateOfBirth = new IWTimestamp(user.getDateOfBirth()); dateOfBirth.setMonth(1); dateOfBirth.setDay(1); Age age = new Age(dateOfBirth.getDate()); if (age.getYears(course.getStartDate()) < 6 || age.getYears(course.getStartDate()) > 18) { outsideAgeRange.add(user); continue; } if (!getUserBusiness().isCitizenOfDefaultCommune(user)) { outsideCommune.add(user); continue; } group.addGroup(user); imported.add(user); } else { alreadyImported.add(user); } } catch (FinderException e) { noUserFound.add(personalID); } } else { invalidPersonalID.add(personalID); } } map.put(FSKConstants.REGISTRATION_CODE_REGISTERED, imported); map.put(FSKConstants.REGISTRATION_CODE_ALREADY_REGISTERED, alreadyImported); map.put(FSKConstants.REGISTRATION_CODE_OUTSIDE_COMMUNE, outsideCommune); map.put(FSKConstants.REGISTRATION_CODE_OUTSIDE_AGE_RANGE, outsideAgeRange); map.put(FSKConstants.REGISTRATION_CODE_INVALID_PERSONAL_ID, invalidPersonalID); map.put(FSKConstants.REGISTRATION_CODE_NO_USER_FOUND, noUserFound); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return map; }
From source file:it.filippovitale.fineco2qif.logic.ExcelSheetAnalysisLogic.java
License:Apache License
public static List<String[]> getCells(HSSFSheet sheet, Short[] columnAbsolutePositions, boolean looseConstraint) { List<String[]> cells = new ArrayList<String[]>(); for (int rowAbsolutePosition = sheet.getFirstRowNum() + 1; rowAbsolutePosition <= sheet .getLastRowNum(); rowAbsolutePosition++) { HSSFRow row = sheet.getRow(rowAbsolutePosition); if (row == null) { if (looseConstraint) { log.debug("empty row in the absolute position \"" + rowAbsolutePosition + "\""); } else { log.warn("row in the absolute position \"" + rowAbsolutePosition + "\" has problem"); }//from w w w .j a va 2 s. com continue; } String cellStringValues[] = new String[5]; for (int columnRelativePosition = 0; columnRelativePosition < cellStringValues.length; columnRelativePosition++) { HSSFCell cell = row.getCell(columnAbsolutePositions[columnRelativePosition]); String cellStringValue = cell != null ? cell.getStringCellValue() : null; if (cellStringValue != null && cellStringValue.trim().equals("")) { cellStringValue = null; } cellStringValues[columnRelativePosition] = cellStringValue; } if (cellStringValues[0] == null && cellStringValues[1] == null && cellStringValues[2] == null && cellStringValues[3] == null && cellStringValues[4] == null) { if (looseConstraint) { log.debug("empty row in the absolute position \"" + rowAbsolutePosition + "\""); } else { log.warn("row in the absolute position \"" + rowAbsolutePosition + "\" has problem, it's {null, null, null, null, null}"); } } else { cells.add(cellStringValues); } } dumpCells(cells); validateCells(cells, looseConstraint); return cells; }
From source file:it.filippovitale.fineco2qif.logic.ExcelSheetAnalysisLogic.java
License:Apache License
private static void dumpSheet(HSSFSheet sheet) { if (sheet == null) { log.debug("The sheet to dump is null!"); return;//from w w w . j ava2 s . c o m } for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) { log.debug("row#" + i + "="); HSSFRow row = sheet.getRow(i); if (row == null) { log.debug("\t| " + NULL_RAPPRESENTATION); continue; } for (int j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) { HSSFCell cell = row.getCell((short) j); String cellValue = getCellValue(cell); log.debug("\t| " + cellValue); } log.debug("\n"); } }
From source file:javaapplication2.Frame1.java
void fillData(File file) { int index = -1; HSSFWorkbook workbook = null;/*from w w w .ja v a 2 s . c o m*/ try { try { FileInputStream inputStream = new FileInputStream(file); workbook = new HSSFWorkbook(inputStream); } catch (IOException ex) { Logger.getLogger(Frame1.class.getName()).log(Level.SEVERE, null, ex); } String[] strs = new String[workbook.getNumberOfSheets()]; //get all sheet names from selected workbook for (int i = 0; i < strs.length; i++) { strs[i] = workbook.getSheetName(i); } JFrame frame = new JFrame("Input Dialog"); String selectedsheet = (String) JOptionPane.showInputDialog(frame, "Which worksheet you want to import ?", "Select Worksheet", JOptionPane.QUESTION_MESSAGE, null, strs, strs[0]); if (selectedsheet != null) { for (int i = 0; i < strs.length; i++) { if (workbook.getSheetName(i).equalsIgnoreCase(selectedsheet)) index = i; } HSSFSheet sheet = workbook.getSheetAt(index); HSSFRow row = sheet.getRow(0); headers.clear(); //int value=row.getLastCellNum(); for (int i = 0; i < row.getLastCellNum(); i++) { HSSFCell cell1 = row.getCell(i); headers.add(cell1.toString()); } data.clear(); for (int j = 1; j < sheet.getLastRowNum() + 1; j++) { Vector d = new Vector(); row = sheet.getRow(j); int noofrows = row.getLastCellNum(); for (int i = 0; i < noofrows; i++) { //To handle empty excel cells HSSFCell cell = row.getCell(i, org.apache.poi.ss.usermodel.Row.CREATE_NULL_AS_BLANK); d.add(cell.toString()); } d.add("\n"); data.add(d); } } else { return; } } catch (Exception e) { e.printStackTrace(); } }
From source file:javaexecelprocess.JavaExecelProcess.java
public long[] getFieldsLen() { // Integer dat = new Integer(7); int iCols = getColumns(); long[] fieldsLen = new long[iCols]; for (int i = 0; i < iCols; i++) { fieldsLen[i] = -1;/*from ww w .j av a 2s.c o m*/ } HSSFSheet activeSheet = wb.getSheetAt(0); int iFirstRow = activeSheet.getFirstRowNum(); int iLastRow = activeSheet.getLastRowNum(); for (int i = iFirstRow + 1; i <= iLastRow; i++) { HSSFRow row = activeSheet.getRow(i); int iFirstCol = row.getFirstCellNum(); int iLastCol = row.getLastCellNum(); for (int j = iFirstCol; j < iLastCol; j++) { HSSFCell cell = row.getCell(j); int cellType = cell.getCellType(); if (HSSFCell.CELL_TYPE_STRING == cellType) { long tmpLen = cell.getStringCellValue().length(); if (fieldsLen[j - iFirstCol] < tmpLen) { fieldsLen[j - iFirstCol] = tmpLen; } } else if (HSSFCell.CELL_TYPE_NUMERIC == cellType) { fieldsLen[j - iFirstCol] = -1; } else { } } } return fieldsLen; }