List of usage examples for org.apache.poi.ss.usermodel Row getLastCellNum
short getLastCellNum();
From source file:org.openelis.bean.WorksheetExcelHelperBean.java
License:Open Source License
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) private int createQcResultCellsForFormat(HSSFSheet sheet, Row row, Row tRow, String nameIndexPrefix, HashMap<String, String> cellNames, WorksheetViewDO wVDO, Integer qcId, ArrayList<WorksheetQcResultViewDO> wqrList, HashMap<String, HashMap<Integer, ArrayList<AnalyteParameterViewDO>>> apMap) { int c, i, r;//from w w w . ja v a 2 s .c o m String cellNameIndex, name; ArrayList<AnalyteParameterViewDO> anaParams, apList; DecimalFormat df; HashMap<Integer, ArrayList<AnalyteParameterViewDO>> pMap; Cell cell, tCell; Name cellName; AnalyteParameterViewDO apVDO; df = new DecimalFormat(); df.setGroupingUsed(false); df.setMaximumFractionDigits(10); i = 0; r = row.getRowNum(); for (WorksheetQcResultViewDO wqrVDO : wqrList) { if (i != 0) { row = sheet.createRow(r); for (c = 0; c < 7; c++) { cell = row.createCell(c); cell.setCellStyle(styles.get("row_no_edit")); } } cellNameIndex = nameIndexPrefix + "." + i; // analyte cell = row.createCell(7); cell.setCellStyle(styles.get("row_no_edit")); cell.setCellValue(wqrVDO.getAnalyteName()); // reportable cell = row.createCell(8); cell.setCellStyle(styles.get("row_no_edit")); cell.setCellValue("N"); apVDO = null; for (c = 9; c < tRow.getLastCellNum() && c < 39; c++) { tCell = tRow.getCell(c); cell = row.createCell(c); cell.setCellStyle(tCell.getCellStyle()); name = cellNames.get( sheet.getSheetName() + "!$" + CellReference.convertNumToColString(tCell.getColumnIndex()) + "$" + (tCell.getRowIndex() + 1)); if (name != null) { cellName = row.getSheet().getWorkbook().createName(); cellName.setNameName(name + "." + cellNameIndex); cellName.setRefersToFormula( sheet.getSheetName() + "!$" + CellReference.convertNumToColString(cell.getColumnIndex()) + "$" + (row.getRowNum() + 1)); } if (tCell.getCellType() == Cell.CELL_TYPE_FORMULA && tCell.getCellFormula() != null) { cell.setCellFormula(tCell.getCellFormula()); } else { setCellValue(cell, wqrVDO.getValueAt(c - 9)); } if ("p1".equals(name) || "p2".equals(name) || "p3".equals(name) || "p_1".equals(name) || "p_2".equals(name) || "p_3".equals(name)) { if (wqrVDO.getValueAt(c - 9) == null) { pMap = apMap.get("Q" + qcId); if (pMap == null) { pMap = new HashMap<Integer, ArrayList<AnalyteParameterViewDO>>(); apMap.put("Q" + qcId, pMap); try { anaParams = analyteParameter.fetchByActiveDate(qcId, Constants.table().QC, wVDO.getCreatedDate().getDate()); for (AnalyteParameterViewDO anaParam : anaParams) { apList = pMap.get(anaParam.getAnalyteId()); if (apList == null) { apList = new ArrayList<AnalyteParameterViewDO>(); pMap.put(anaParam.getAnalyteId(), apList); } apList.add(anaParam); } } catch (NotFoundException nfE) { continue; } catch (Exception anyE) { log.log(Level.SEVERE, "Error retrieving analyte parameters for a qc on worksheet.", anyE); continue; } } apList = pMap.get(wqrVDO.getAnalyteId()); apVDO = null; if (apList != null && apList.size() > 0) apVDO = apList.get(0); if (apVDO != null) { if (("p1".equals(name) || "p_1".equals(name)) && apVDO.getP1() != null) { setCellValue(cell, String.valueOf(apVDO.getP1())); } else if (("p2".equals(name) || "p_2".equals(name)) && apVDO.getP2() != null) { setCellValue(cell, String.valueOf(apVDO.getP2())); } else if (("p3".equals(name) || "p_3".equals(name)) && apVDO.getP3() != null) { setCellValue(cell, String.valueOf(apVDO.getP3())); } } } } } i++; r++; } return r; }
From source file:org.openelis.bean.WorksheetExcelHelperBean.java
License:Open Source License
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) private void createEmptyCellsForFormat(Row row, Row tRow) { int c;/*from ww w . j a va2 s . c o m*/ Cell cell; // analyte cell = row.createCell(7); cell.setCellStyle(styles.get("row_no_edit")); cell.setCellValue("NO ANALYTES DEFINED"); // reportable cell = row.createCell(8); cell.setCellStyle(styles.get("row_no_edit")); cell.setCellValue("N"); for (c = 9; c < tRow.getLastCellNum(); c++) { cell = row.createCell(c); cell.setCellStyle(styles.get("row_no_edit")); cell.setCellValue(""); } }
From source file:org.openepics.discs.ccdb.core.dl.common.ExcelImportFileReader.java
License:Open Source License
/** * This method returns the contents of the first worksheet found in the * Excel workbook file./*from ww w. j a va2 s . com*/ * * @param inputStream * the Excel file to parse. Only Excel file version >=12.0 * supported (.xslx). * @param dataStartIndex * the index of the row where to start parsing the import data. * @param dataRowLength * the length of each row if it contains all the data. This length is usually defined by the Excel * template. * @return Only the lines from the first worksheet that contain a string * value. Lines with the empty first cell are not part of the return * set. Each row is represented as a pair of the row number and a list of columns. */ public static List<Pair<Integer, List<String>>> importExcelFile(InputStream inputStream, int dataStartIndex, final int dataRowLength) { final List<Pair<Integer, List<String>>> result = new ArrayList<>(); try { final XSSFWorkbook workbook = new XSSFWorkbook(inputStream); final XSSFSheet sheet = workbook.getSheetAt(0); for (Row excelRow : sheet) { if (excelRow.getRowNum() < dataStartIndex) { continue; } final String firstColumnValue = Strings .emptyToNull(ExcelCell.asStringOrNull(excelRow.getCell(0), workbook)); if (firstColumnValue != null && !firstColumnValue.trim().isEmpty()) { final List<String> row = new ArrayList<>(); final int rowNumber = excelRow.getRowNum() + 1; final int lastCellIndex = dataRowLength > excelRow.getLastCellNum() ? dataRowLength : excelRow.getLastCellNum(); for (int i = 0; i < lastCellIndex; i++) { row.add(ExcelCell.asStringOrNull(excelRow.getCell(i), workbook)); } result.add(new ImmutablePair<Integer, List<String>>(rowNumber, row)); } } } catch (IOException e) { throw new RuntimeException(e); } return result; }
From source file:org.openepics.names.ui.devices.ExcelImport.java
License:Open Source License
/** * Parses the input stream read from an Excel file, creating devices in the database. If the device already exists, * it's silently ignored./* www . j a v a 2s . c o m*/ * * @param input the input stream * @return an ExcelImportResult object reporting the outcome of the import operation */ public ExcelImportResult parseDeviceImportFile(InputStream input) { init(); try { final XSSFWorkbook workbook = new XSSFWorkbook(input); final XSSFSheet sheet = workbook.getSheetAt(0); for (Row row : sheet) { if (row.getRowNum() > 0) { if (row.getLastCellNum() < 5) { return new ColumnCountFailureExcelImportResult(); } else { final String superSection = ExcelCell.asString(row.getCell(0)); final String section = As.notNull(ExcelCell.asString(row.getCell(1))); final String subsection = As.notNull(ExcelCell.asString(row.getCell(2))); final String discipline = As.notNull(ExcelCell.asString(row.getCell(3))); final String deviceType = As.notNull(ExcelCell.asString(row.getCell(4))); final @Nullable String index = ExcelCell.asString(row.getCell(5)); final @Nullable String description = ExcelCell.asString(row.getCell(6)); final ExcelImportResult addDeviceNameResult = addDeviceName(superSection, section, subsection, discipline, deviceType, index, description, row.getRowNum()); if (addDeviceNameResult instanceof FailureExcelImportResult) { return addDeviceNameResult; } } } } } catch (IOException e) { throw new RuntimeException(e); } namePartService.batchAddDevices(newDevices); return new SuccessExcelImportResult(); }
From source file:org.openepics.names.ui.export.ExcelExport.java
License:Open Source License
private Cell appendCell(Row row, String value) { final Cell cell = row.createCell(row.getLastCellNum() == -1 ? 0 : row.getLastCellNum()); cell.setCellType(Cell.CELL_TYPE_STRING); cell.setCellValue(value);//from w w w . java 2 s . c o m return cell; }
From source file:org.opentestsystem.delivery.testreg.upload.ExcelUtils.java
License:Open Source License
private Object[] getCellValues(final Row row, final MissingCellPolicy policy) { final List<Object> excelColumnList = new ArrayList<Object>(); final DataFormatter dataFormat = new DataFormatter(); final int lastCellNo = row.getLastCellNum(); for (int cellNum = 0; cellNum < lastCellNo; cellNum++) { final Cell cell = row.getCell(cellNum, policy); if (cell != null) { switch (cell.getCellType()) { case XSSFCell.CELL_TYPE_STRING: excelColumnList.add(cell.getStringCellValue()); break; case XSSFCell.CELL_TYPE_BOOLEAN: cell.setCellType(XSSFCell.CELL_TYPE_STRING); excelColumnList.add(cell.getStringCellValue()); break; case XSSFCell.CELL_TYPE_NUMERIC: excelColumnList.add(dataFormat.formatCellValue(cell)); break; case XSSFCell.CELL_TYPE_BLANK: excelColumnList.add(""); break; case XSSFCell.CELL_TYPE_FORMULA: excelColumnList.add(cell.getCellFormula()); break; case XSSFCell.CELL_TYPE_ERROR: excelColumnList.add(cell.getErrorCellValue()); break; default: excelColumnList.add(cell.toString()); }// www.j a v a 2 s . c o m } } return excelColumnList.toArray(new Object[excelColumnList.size()]); }
From source file:org.patientview.ibd.util.MedicationImporter.java
License:Open Source License
public void run(String excelFileLocation, String outputFileLocation) { this.outputFileLocation = outputFileLocation; // first check to see if the file already exists and if it does delete it so we dont append more sql // to what exists in it from a previous export if (fileExists(outputFileLocation)) { deleteFile(outputFileLocation);// w w w .ja v a2 s.com } try { // try and read the file InputStream inp = new FileInputStream(excelFileLocation); // create a spreadsheet so we can move through it Workbook wb = WorkbookFactory.create(inp); Sheet sheet = wb.getSheetAt(0); for (Row row : sheet) { String medicationTypeName = null; String medicationName = null; String medicationDosages = null; // first row is the title of the columns if (row.getRowNum() > 0) { for (int cn = 0; cn < row.getLastCellNum(); cn++) { // we only expect 3 cols of data if (cn > MAX_COLS) { break; } Cell cell = row.getCell(cn); if (cell != null) { cell.setCellType(Cell.CELL_TYPE_STRING); String value = cell.getStringCellValue(); // check what cell it is and set data we need if (cn == MEDICATION_TYPE_NAME_COL) { medicationTypeName = value.trim(); } else if (cn == MEDICATION_NAME_COL) { medicationName = value.trim(); } else if (cn == MEDICATION_DOSAGES_COL) { medicationDosages = value.trim(); } if (medicationTypeName != null && medicationTypeName.length() > 0 && medicationName != null && medicationName.length() > 0 && medicationDosages != null && medicationDosages.length() > 0) { // first check if a medication type already exists with this name else create MedicationType medicationType = medicationTypes.get(medicationTypeName); if (medicationType == null) { medicationType = new MedicationType(); medicationType.setName(medicationTypeName); medicationType.setMedications(new ArrayList<Medication>()); medicationTypes.put(medicationTypeName, medicationType); // set the id and increment for the next one medicationType.setId(medicationTypeCurrentId); medicationTypeCurrentId++; } // then create a medication object that we can assign the dosages Medication medication = new Medication(); medication.setName(medicationName); // now parse any dosages and assign to the medication medication.setAllowedDosages(parseMedicationDosages(medicationDosages)); // set the id and increment for the next one medication.setId(medicationCurrentId); medicationCurrentId++; // add this medication to the medication type medicationType.getMedications().add(medication); } } } } } } catch (FileNotFoundException e) { System.out.println("Could not find file " + e); } catch (IOException e) { System.out.println("Could not read file " + e); } catch (Exception e) { System.out.println("Unknown error " + e); } // if the file was processed and we have any objects then build some sql statements if (!medicationTypes.isEmpty()) { for (MedicationType medicationType : medicationTypes.values()) { // first enter the medications and dosages buildMedicationSqlInsert(medicationType.getMedications()); // then buld the sql for the medication type and map the medications to it buildMedicationTypeSqlInsert(medicationType); } } System.out.println("Import file created " + outputFileLocation); }
From source file:org.patientview.radar.util.RadarPhase2ExcelDataToSqlMapper.java
License:Open Source License
public static void main(String params[]) { InputStream inp = null;/* w w w. j av a 2s . c o m*/ try { /************** 1. first create the prd codes sql ***************/ // this is the file from radar originally called ERA_EDTA_new_PRD_codes_27042012_def for NDT_RADAR inp = new FileInputStream(BASE_PATH + "input/prd_codes_and_working_group.xls"); Workbook wb = WorkbookFactory.create(inp); Sheet sheet = wb.getSheetAt(0); // each list item represents a row to insert List<List<String>> dataList = new ArrayList<List<String>>(); //iterate through the rows in excel file for (Row row : sheet) { // ignore non data rows if (row.getRowNum() < FIRST_DATA_ROW) { continue; } else if (row.getRowNum() > LAST_DATA_ROW) { break; } List<String> values = new ArrayList<String>(); // iterate through cells for (int cn = 0; cn < row.getLastCellNum(); cn++) { Cell cell = row.getCell(cn); // ignore non data cells if (cn > 23) { break; } String value = ""; if (cell != null) { cell.setCellType(Cell.CELL_TYPE_STRING); value = cell.getStringCellValue(); } // convert x values to 1 which means true, or blank to 0 which means false if ((cn >= FIRST_BOOLEAN_FIELD && cn <= LAST_BOOLEAN_FIELD)) { value = value.equals("x") ? "1" : "0"; } values.add(value); } dataList.add(values); } StringBuilder outputText = new StringBuilder(); StringBuilder prdSql = new StringBuilder(); String sqlBaseInsert = "INSERT INTO rdr_prd_code(ERA_EDTA_PRD_code, ERA_EDTA_primaryRenalDiagnosisTerm, " + "histology, clinicalHistory, familyHistory, clinicalExam, biochemistry, immunology, " + "urineAnalysis, " + "imaging, geneTest, otherCriteriaAndNotes, " + "SNOMED_CT_conceptIdentifierForFocusConcept, " + "SNOMED_CT_fullySpecifiedName, " + "SNOMED_CT_expressionConstraint, majorHeading, mappingToOldPRDCode, " + "mappingToOldPRDTerm, ERA_EDTA_defaultSortOrder, geneticsHomeReferenceLink, " + "nationalCenterForBiotechnologyLink, ICD_10_code, ICD10_rubricTerm, alternativesearchTerms) " + "VALUES ("; int index = 0; // for each row in the data list create an sql insert statement for (List<String> row : dataList) { String sqlInsert = sqlBaseInsert; int valueIndex = 0; for (String value : row) { value = value.replace("'", "").replace("\"", ""); sqlInsert += "'" + value + "'" + (valueIndex != row.size() - 1 ? "," : ""); valueIndex++; } sqlInsert += ");" + System.getProperty("line.separator"); prdSql.append(sqlInsert); index++; } // append to output text - output text will eventually be written to a file outputText.append(prdSql + System.getProperty("line.separator")); /************** 2. create the working groups sql ***************/ Row row = sheet.getRow(1); List<String> workingGroups = new ArrayList<String>(); // iterate through all working groups for (Cell cell : row) { if (cell.getColumnIndex() < FIRST_WORKING_GROUP_INDEX) { continue; } else if (cell.getColumnIndex() > LAST_WORKING_GROUP_INDEX) { break; } cell.setCellType(Cell.CELL_TYPE_STRING); String value = cell.getStringCellValue(); value = value.replace("'", "\\'"); workingGroups.add(value); } // create sql for working groups sql insert String workingGroupSql = "" + System.getProperty("line.separator"); int workingGroupIndex = 0; for (String workingGroup : workingGroups) { String unitCode = workingGroup.split(" ")[0] + workingGroupIndex; // this is id, has to be unique workingGroupSql += "INSERT INTO unit(unitcode, name, shortName, sourceType) VALUES('" + unitCode + "', '" + workingGroup + "', '','radargroup');" + System.getProperty("line.separator"); workingGroupIndex++; } // append to output text - output text will eventually be written to a file outputText.append(workingGroupSql + System.getProperty("line.separator")); /************** 3. create the mapping table sql - this is the tricky bit! ***************/ List<List<String>> mappingData = new ArrayList<List<String>>(); // for each working group collect mapping values to working group for (int columnIndex = FIRST_WORKING_GROUP_INDEX; columnIndex < LAST_WORKING_GROUP_INDEX; columnIndex++) { List<String> list = new ArrayList<String>(); for (int rowIndex = FIRST_DATA_ROW; rowIndex <= LAST_DATA_ROW; rowIndex++) { Row mappingRow = sheet.getRow(rowIndex); Cell cell = mappingRow.getCell(columnIndex); String value = "0"; if (cell != null) { cell.setCellType(Cell.CELL_TYPE_STRING); value = cell.getStringCellValue(); } list.add(value); } mappingData.add(list); } // create list of prd ids List<String> prdIds = new ArrayList<String>(); for (int i = FIRST_DATA_ROW; i <= LAST_DATA_ROW; i++) { Row aRow = sheet.getRow(i); Cell cell = aRow.getCell(0); cell.setCellType(Cell.CELL_TYPE_STRING); String value = cell.getStringCellValue(); prdIds.add(value); } // create sql insert statements based on where working group and disease intersect String mappingSql = ""; String baseSql = "INSERT INTO rdr_diagnosis_mapping(workingGroup, PRDCode, ordering) VALUES("; for (int i = 0; i < mappingData.size(); i++) { String sql = ""; List<String> list = mappingData.get(i); for (int j = 0; j < list.size(); j++) { sql = baseSql; String value = list.get(j); if (!value.equals("0")) { sql += "'" + (workingGroups.get(i).split(" ")[0] + i) + "', '" + prdIds.get(j) + "','" + value + "');"; if (!sql.equals(baseSql)) { mappingSql += sql + System.getProperty("line.separator"); } } } } outputText.append(mappingSql); // output all sql stuff to file FileWriter fileWriter = new FileWriter(BASE_PATH + "output/phase2Data.sql"); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); bufferedWriter.write(outputText.toString()); //Close the output stream bufferedWriter.close(); } catch (Exception e) { //To change body of catch statement use File | Settings | File Templates. LOGGER.error(e.getMessage()); LOGGER.debug(e.getMessage(), e); } }
From source file:org.paxml.bean.excel.ReadExcelTag.java
License:Open Source License
private Iterator doBasic(Context context) throws Exception { return new Iterator() { private Iterator<Row> it; private int index; private Map<Integer, String> headers = new HashMap<Integer, String>(); private void start() { boolean ok = false; try { Sheet s = getExcelSheet(false); it = s.iterator();/*from w ww.j a v a 2 s. co m*/ // find the start row if (log.isDebugEnabled()) { log.debug("Start reading from row " + Math.max(1, firstRow) + " of sheet: " + s.getSheetName()); } for (int i = 1; i < firstRow && it.hasNext(); i++) { it.next(); index++; } ok = true; } finally { if (!ok) { end(); } } } private void end() { it = null; file.close(); } @Override public boolean hasNext() { if (it == null) { start(); } if (lastRow > 0 && index > lastRow - 1) { end(); return false; } try { boolean has = it.hasNext(); if (!has) { end(); } return has; } catch (Exception e) { end(); throw new PaxmlRuntimeException(e); } } @Override public Object next() { try { Row row = it.next(); Object r = readRow(row); index++; return r; } catch (Exception e) { end(); throw new PaxmlRuntimeException(e); } } @Override public void remove() { throw new UnsupportedOperationException(); } private Map<Object, Object> readRow(Row row) { final int firstCell = Math.max(row.getFirstCellNum(), _firstColumn); final int lastCell = _lastColumn < 0 ? row.getLastCellNum() - 1 : Math.min(row.getLastCellNum() - 1, _lastColumn); if (log.isDebugEnabled()) { log.debug("Reading cells: " + new CellReference(index, firstCell).formatAsString() + ":" + new CellReference(index, lastCell).formatAsString()); } Map<Object, Object> result = new LinkedHashMap<Object, Object>(); for (int i = firstCell; i <= lastCell; i++) { Cell cell = row.getCell(i); if (cell != null) { Object value = file.getCellValue(cell); // dual keys for the same value result.put(i, value); String key = headers.get(i); if (key == null) { key = new CellReference(-1, i).formatAsString(); headers.put(i, key); } result.put(key, value); } } return result; } }; }
From source file:org.pentaho.di.trans.steps.excelinput.poi.PoiSheet.java
License:Apache License
public KCell[] getRow(int rownr) { if (rownr < sheet.getFirstRowNum()) { return new KCell[] {}; } else if (rownr > sheet.getLastRowNum()) { throw new ArrayIndexOutOfBoundsException("Read beyond last row: " + rownr); }//from w w w . j av a 2s .c o m Row row = sheet.getRow(rownr); if (row == null) { // read an empty row return new KCell[] {}; } int cols = row.getLastCellNum(); if (cols < 0) { // this happens if a row has no cells, POI returns -1 then return new KCell[] {}; } PoiCell[] xlsCells = new PoiCell[cols]; for (int i = 0; i < cols; i++) { Cell cell = row.getCell(i); if (cell != null) { xlsCells[i] = new PoiCell(cell); } } return xlsCells; }