List of usage examples for org.apache.poi.ss.usermodel Row getLastCellNum
short getLastCellNum();
From source file:utilities.XLSTemplateUploadManager.java
License:Open Source License
private Option getOption(Row row, String listName) throws ApplicationException, Exception { Option o = new Option(); int lastCellNum = row.getLastCellNum(); o.optionList = listName;/*from w w w .ja v a2s. c o m*/ o.value = XLSUtilities.getTextColumn(row, "name", choicesHeader, lastCellNum, null); o.display_name = XLSUtilities.getTextColumn(row, "display_name", choicesHeader, lastCellNum, null); getLabels(row, lastCellNum, choicesHeader, o.labels, "choice"); if (merge) { // Attempt to get existing column name String n = optionNames.get(listName + "__" + o.value); if (n != null) { o.columnName = n; } else { o.columnName = GeneralUtilityMethods.cleanName(o.value, false, false, false); } } else { o.columnName = GeneralUtilityMethods.cleanName(o.value, false, false, false); } o.cascade_filters = new HashMap<String, String>(); for (String key : choiceFilterHeader.keySet()) { String value = XLSUtilities.getTextColumn(row, key, choicesHeader, lastCellNum, null); if (value != null) { o.cascade_filters.put(key, value); } } o.published = false; // Default to unpublised TODO work out when this can be set to published validateOption(o, rowNumChoices); return o; }
From source file:utilities.XLSTemplateUploadManager.java
License:Open Source License
private void getHeaders() throws ApplicationException { choiceFilterHeader = new HashMap<String, Integer>(); HashMap<String, String> langMap = new HashMap<String, String>(); // Get survey sheet headers while (rowNumSurvey <= lastRowNumSurvey) { Row row = surveySheet.getRow(rowNumSurvey++); if (row != null) { surveyHeader = XLSUtilities.getHeader(row, localisation, rowNumSurvey, "survey"); // Add languages in order they exist in the header hence won't use keyset of surveyHeader int lastCellNum = row.getLastCellNum(); for (int i = 0; i <= lastCellNum; i++) { Cell cell = row.getCell(i); if (cell != null) { String name = cell.getStringCellValue(); if (name.startsWith("label::")) { // Only check the question label for languages, any others will be assumed to be errors String[] sArray = name.split("::"); if (sArray.length > 0) { String exists = langMap.get(sArray[1]); if (exists == null) { langMap.put(sArray[1], sArray[1]); survey.languages.add(new Language(0, sArray[1])); }/*from w w w. j ava 2 s . co m*/ } } } } // Get security roles for (String h : surveyHeader.keySet()) { if (h.startsWith("role::")) { if (columnRoleHeader == null) { columnRoleHeader = new HashMap<String, Integer>(); } columnRoleHeader.put(h, surveyHeader.get(h)); String[] roleA = h.split("::"); if (roleA.length > 1) { survey.roles.put(h, new Role(roleA[1])); } } } break; } } // Get choice sheet header if (choicesSheet != null) { while (rowNumChoices <= lastRowNumChoices) { Row row = choicesSheet.getRow(rowNumChoices++); if (row != null) { choicesHeader = XLSUtilities.getHeader(row, localisation, rowNumChoices, "choices"); // Get the headers for filters for (String h : choicesHeader.keySet()) { if (h.equals("list name") || h.equals("name") || h.equals("label") || h.equals("display_name") || h.startsWith("label::") || h.equals("image") || h.startsWith("image::") // deprecate? || h.startsWith("media::image") || h.equals("audio") || h.startsWith("audio::") // deprecate? || h.startsWith("media::audio") || h.equals("video") || h.startsWith("media::video") || h.startsWith("video::")) { // deprecate? continue; } // The rest must be filter columns choiceFilterHeader.put(h, choicesHeader.get(h)); } break; } } } // Add a default language if needed if (survey.languages.size() == 0) { survey.languages.add(new Language(0, "language")); useDefaultLanguage = true; } // Get Setting sheet headers if (settingsSheet != null) { while (rowNumSettings <= lastRowNumSettings) { Row row = settingsSheet.getRow(rowNumSettings++); if (row != null) { settingsHeader = XLSUtilities.getHeader(row, localisation, rowNumSettings, "settings"); break; } } // Add security roles if (settingsHeader != null) { for (String h : settingsHeader.keySet()) { if (h.startsWith("role::")) { if (rowRoleHeader == null) { rowRoleHeader = new HashMap<String, Integer>(); } rowRoleHeader.put(h, settingsHeader.get(h)); String[] roleA = h.split("::"); if (roleA.length > 1) { survey.roles.put(h, new Role(roleA[1])); } } } } } }
From source file:utilities.XLSTemplateUploadManager.java
License:Open Source License
private Question getQuestion(Row row, int formIndex, int questionIndex) throws ApplicationException, Exception { Question q = new Question(); int lastCellNum = row.getLastCellNum(); // 1. Question type String type = XLSUtilities.getTextColumn(row, "type", surveyHeader, lastCellNum, null); // 2. Question name q.name = XLSUtilities.getTextColumn(row, "name", surveyHeader, lastCellNum, null); // Check type is not null if (type == null && q.name != null) { throw XLSUtilities.getApplicationException(localisation, "tu_mt", rowNumSurvey, "survey", null, null, null);// w w w . ja v a 2 s .c om } else if (type == null && q.name == null) { return null; // blank row } q.type = convertType(type, q); if (q.type.equals("geopoint") || q.type.equals("geotrace") || q.type.equals("geoshape")) { q.name = "the_geom"; } // 3. Labels getLabels(row, lastCellNum, surveyHeader, q.labels, q.type); if (merge) { String n = questionNames.get(q.name); if (n != null) { q.columnName = n; } else { q.columnName = GeneralUtilityMethods.cleanName(q.name, true, true, true); } } else { q.columnName = GeneralUtilityMethods.cleanName(q.name, true, true, true); } // display name q.display_name = XLSUtilities.getTextColumn(row, "display_name", surveyHeader, lastCellNum, null); // 4. choice filter q.choice_filter = XLSUtilities.getTextColumn(row, "choice_filter", surveyHeader, lastCellNum, null); q.choice_filter = GeneralUtilityMethods.cleanXlsNames(q.choice_filter); // 5. Constraint q.constraint = XLSUtilities.getTextColumn(row, "constraint", surveyHeader, lastCellNum, null); q.constraint = GeneralUtilityMethods.cleanXlsNames(q.constraint); // 6. Constraint message q.constraint_msg = XLSUtilities.getTextColumn(row, "constraint_message", surveyHeader, lastCellNum, null); if (q.constraint_msg == null) { q.constraint_msg = XLSUtilities.getTextColumn(row, "constraint-msg", surveyHeader, lastCellNum, null); // as used by enketo } // 7. Relevant q.relevant = XLSUtilities.getTextColumn(row, "relevant", surveyHeader, lastCellNum, null); q.relevant = GeneralUtilityMethods.cleanXlsNames(q.relevant); // 7. Repeat count if (q.type.equals("begin repeat")) { q.repeatCount = XLSUtilities.getTextColumn(row, "repeat_count", surveyHeader, lastCellNum, null); } // 8. Default q.defaultanswer = XLSUtilities.getTextColumn(row, "default", surveyHeader, lastCellNum, null); // 9. Readonly q.readonly = getBooleanColumn(row, "readonly", surveyHeader, lastCellNum); // 10. Appearance q.appearance = XLSUtilities.getTextColumn(row, "appearance", surveyHeader, lastCellNum, null); q.appearance = GeneralUtilityMethods.cleanXlsNames(q.appearance); // 11. Parameters String paramString = XLSUtilities.getTextColumn(row, "parameters", surveyHeader, lastCellNum, null); q.paramArray = GeneralUtilityMethods.convertParametersToArray(paramString); // 12. autoplay q.autoplay = XLSUtilities.getTextColumn(row, "autoplay", surveyHeader, lastCellNum, null); // 13. body::accuracyThreshold q.accuracy = XLSUtilities.getTextColumn(row, "body::accuracyThreshold", surveyHeader, lastCellNum, null); // 14. Required q.required = getBooleanColumn(row, "required", surveyHeader, lastCellNum); // 15. Required Message q.required_msg = XLSUtilities.getTextColumn(row, "required_message", surveyHeader, lastCellNum, null); // 16. Calculation q.calculation = XLSUtilities.getTextColumn(row, "calculation", surveyHeader, lastCellNum, null); q.calculation = GeneralUtilityMethods.cleanXlsNames(q.calculation); // 17. Display Name q.display_name = XLSUtilities.getTextColumn(row, "display_name", surveyHeader, lastCellNum, null); // 18. Compressed if (q.type.equals("select")) { q.compressed = true; } // 19. body::intent q.intent = XLSUtilities.getTextColumn(row, "body::intent", surveyHeader, lastCellNum, null); // Add Column Roles if (columnRoleHeader != null && columnRoleHeader.size() > 0) { for (String h : columnRoleHeader.keySet()) { if (getBooleanColumn(row, h, surveyHeader, lastCellNum)) { Role r = survey.roles.get(h); if (r != null) { if (r.column_filter_ref == null) { r.column_filter_ref = new ArrayList<RoleColumnFilterRef>(); } r.column_filter_ref.add(new RoleColumnFilterRef(formIndex, questionIndex)); } } } } /* * Handle Groups */ if (q.type.equals("begin group")) { Stack<Question> groupStack = getGroupStack(formIndex); groupStack.push(q); if (q.appearance != null && q.appearance.contains("table-list")) { inTableListGroup = true; foundSelectInTableListGroup = false; justStartedTableListGroup = true; } else { inTableListGroup = false; } } if (q.type.equals("end group")) { Stack<Question> groupStack = getGroupStack(formIndex); if (groupStack.isEmpty()) { Form f = survey.forms.get(formIndex); throw XLSUtilities.getApplicationException(localisation, "tu_eegm", rowNumSurvey, "survey", f.name, null, null); } Question currentGroupQuestion = groupStack.pop(); if (inTableListGroup && !foundSelectInTableListGroup) { throw XLSUtilities.getApplicationException(localisation, "tu_need_s", rowNumSurvey, "survey", currentGroupQuestion.name, null, null); } inTableListGroup = false; if (q.name != null && q.name.trim().length() > 0 && !q.name.endsWith("_groupEnd")) { // ignore end groups that end with _groupEnd as they were generated by old xls exports // Validate the provided group name against the current group if (!q.name.equals(currentGroupQuestion.name)) { throw XLSUtilities.getApplicationException(localisation, "tu_eeg", rowNumSurvey, "survey", q.name, currentGroupQuestion.name, null); } } else { // Set the name of the end group to its group q.name = currentGroupQuestion.name; } } /* * Validate questions inside table list group */ if (inTableListGroup) { if (!justStartedTableListGroup) { if (!q.type.startsWith("select")) { throw XLSUtilities.getApplicationException(localisation, "tu_ns", rowNumSurvey, "survey", q.type, null, null); } else { foundSelectInTableListGroup = true; } } justStartedTableListGroup = false; } /* * Derived Values */ // 1. Source if (q.type.equals("begin group") || q.type.equals("end group") || q.type.equals("begin repeat")) { q.source = null; } else { q.source = "user"; } // 2. Visibility q.visible = convertVisible(type); return q; }
From source file:vn.com.mks.ca.Setting.java
License:Apache License
/** * [Give the description for method]./*from w w w . j a v a 2s .co m*/ * @param sheetName * @param rowIdx start from 0 * @return */ private String[] getDataRow(String sheetName, int rowIdx) { Sheet sheet = workbook.getSheet(sheetName); if (sheet == null) { return null; } Row row = sheet.getRow(rowIdx); if (row == null) { return null; } short minColIx = row.getFirstCellNum(); short maxColIx = row.getLastCellNum(); String[] lstData = new String[maxColIx - minColIx]; Cell cell; Object value; int i = 0; for (short colIx = minColIx; colIx < maxColIx; colIx++) { cell = row.getCell(colIx); if (cell == null) { continue; } value = PoiUtil.getValue(cell); if (value instanceof Date) { lstData[i++] = CommonUtil.formatDate((Date) value, Constant.DEF_DATEFMT); } else if (value instanceof Double) { Double dblValue = (Double) value; lstData[i++] = String.valueOf(dblValue.intValue()); } else if (value != null) { lstData[i++] = value.toString(); } else { lstData[i++] = CHARA.BLANK; } } return lstData; }
From source file:weka.core.converters.ExcelLoader.java
License:Open Source License
/** * Determines and returns (if possible) the structure (internally the header) * of the data set as an empty set of instances. * /*w w w . j a v a2 s .c o m*/ * @return the structure of the data set as an empty set of Instances * @throws IOException if an error occurs */ @Override public Instances getStructure() throws IOException { if (m_sourceStream == null) { throw new IOException("No source has been specified"); } if (m_structure == null) { try { m_Workbook = WorkbookFactory.create(m_sourceStream); m_SheetIndex.setUpper(m_Workbook.getNumberOfSheets() - 1); Sheet sheet = m_Workbook.getSheetAt(m_SheetIndex.getIndex()); if (sheet.getLastRowNum() == 0) { throw new IllegalStateException("No rows in sheet #" + m_SheetIndex.getSingleIndex()); } ArrayList<Attribute> atts = new ArrayList<Attribute>(); Row row = sheet.getRow(0); for (int i = 0; i < row.getLastCellNum(); i++) { Cell cell = row.getCell(i); switch (cell.getCellType()) { case Cell.CELL_TYPE_BLANK: case Cell.CELL_TYPE_ERROR: atts.add(new Attribute("column-" + (i + 1))); break; case Cell.CELL_TYPE_NUMERIC: atts.add(new Attribute("" + cell.getNumericCellValue())); break; default: atts.add(new Attribute(cell.getStringCellValue())); } } m_structure = new Instances("WekaExcel", atts, 0); } catch (IOException ioe) { // just re-throw it throw ioe; } catch (Exception e) { throw new RuntimeException(e); } } return new Instances(m_structure, 0); }
From source file:weka.core.converters.ExcelLoader.java
License:Open Source License
/** * Return the full data set. If the structure hasn't yet been determined by a * call to getStructure then method should do so before processing the rest of * the data set./*from w w w . ja va 2s . c o m*/ * * @return the structure of the data set as an empty set of Instances * @throws IOException if there is no source or parsing fails */ @Override public Instances getDataSet() throws IOException { if (m_sourceStream == null) { throw new IOException("No source has been specified"); } if (getRetrieval() == INCREMENTAL) { throw new IOException("Cannot mix getting Instances in both incremental and batch modes"); } setRetrieval(BATCH); if (m_structure == null) { getStructure(); } Instances result = null; try { // collect data Vector<Object[]> data = new Vector<Object[]>(); boolean newHeader = false; int[] attType = new int[m_structure.numAttributes()]; Sheet sheet = m_Workbook.getSheetAt(m_SheetIndex.getIndex()); for (int i = 1; i <= sheet.getLastRowNum(); i++) { Object[] dataRow = new Object[m_structure.numAttributes()]; data.add(dataRow); Row row = sheet.getRow(i); for (int n = 0; n < row.getLastCellNum(); n++) { Cell cell = row.getCell(n); switch (cell.getCellType()) { case Cell.CELL_TYPE_BLANK: case Cell.CELL_TYPE_ERROR: dataRow[n] = null; break; case Cell.CELL_TYPE_NUMERIC: dataRow[n] = cell.getNumericCellValue(); break; default: if ((m_MissingValue.length() > 0) && cell.getStringCellValue().equals(m_MissingValue)) { dataRow[n] = null; } else { dataRow[n] = cell.getStringCellValue(); attType[n] = Attribute.NOMINAL; newHeader = true; } } } } // new structure necessary? if (newHeader) { ArrayList<Attribute> atts = new ArrayList<Attribute>(); for (int i = 0; i < attType.length; i++) { if (attType[i] == Attribute.NUMERIC) { atts.add(new Attribute(m_structure.attribute(i).name())); } else if (attType[i] == Attribute.NOMINAL) { HashSet<String> strings = new HashSet<String>(); for (int n = 0; n < data.size(); n++) { if (data.get(n)[i] != null) { strings.add(data.get(n)[i].toString()); } } ArrayList<String> attValues = new ArrayList<String>(strings); Collections.sort(attValues); atts.add(new Attribute(m_structure.attribute(i).name(), attValues)); } else { throw new IllegalStateException("Unhandlded attribute type: " + attType[i]); } } m_structure = new Instances("WekaExcel", atts, 0); } // generate output data result = new Instances(m_structure, data.size()); for (int i = 0; i < data.size(); i++) { double[] values = new double[m_structure.numAttributes()]; Object[] dataRow = data.get(i); for (int n = 0; n < dataRow.length; n++) { if (dataRow[n] == null) { values[n] = Utils.missingValue(); } else if (attType[n] == Attribute.NOMINAL) { values[n] = m_structure.attribute(n).indexOfValue((String) dataRow[n]); } else if (attType[n] == Attribute.NUMERIC) { values[n] = ((Number) dataRow[n]).doubleValue(); } else { throw new IllegalStateException("Unhandlded attribute type: " + attType[n]); } } Instance inst = new DenseInstance(1.0, values); result.add(inst); } // close the stream m_sourceStream.close(); } catch (Exception ex) { System.err.println("Failed to load Excel document"); ex.printStackTrace(); // ignored } return result; }
From source file:workbench.db.importer.ExcelReader.java
License:Apache License
@Override public List<String> getHeaderColumns() { if (headerColumns == null) { headerColumns = new ArrayList<>(); Row row = dataSheet.getRow(0); int colCount = row != null ? row.getLastCellNum() : 0; if (row == null || colCount == 0) { LogMgr.logError("ExcelReader.getHeaderColumns()", "Cannot retrieve column names because no data is available in the first row of the sheet: " + dataSheet.getSheetName(), null);/* w w w.j a va 2 s . co m*/ String msg = ResourceMgr.getFormattedString("ErrExportNoCols", dataSheet.getSheetName()); messages.append(msg); messages.appendNewLine(); return headerColumns; } for (int i = 0; i < colCount; i++) { Cell cell = row.getCell(i); Object value = getCellValue(cell); if (value != null) { headerColumns.add(value.toString()); } else { headerColumns.add("Col" + Integer.toString(i)); } } } return headerColumns; }
From source file:workbench.db.importer.ExcelReader.java
License:Apache License
@Override public List<Object> getRowValues(int rowIndex) { Row row = dataSheet.getRow(rowIndex); ArrayList<Object> values = new ArrayList<>(); if (row == null) return values; int nullCount = 0; int colCount = row.getLastCellNum(); for (int col = 0; col < colCount; col++) { Cell cell = row.getCell(col);/*ww w . j av a2 s . c o m*/ // treat rows with merged cells as "empty" if (isMerged(cell)) { LogMgr.logDebug("ExcelReader.getRowValues()", dataSheet.getSheetName() + ": column:" + cell.getColumnIndex() + ", row:" + cell.getRowIndex() + " is merged. Ignoring row!"); return Collections.emptyList(); } Object value = getCellValue(cell); if (value == null) { nullCount++; } values.add(value); } if (nullCount == values.size()) { // return an empty list if all columns are null values.clear(); } return values; }
From source file:XlsUtils.XlsComparator.java
public static boolean comparaFila(Row fila1, Row fila2, StringBuilder cache) { boolean res = true; int numCell1; int numCell2; Cell cell1;/*from ww w . j a v a 2 s.co m*/ Cell cell2; try { numCell1 = fila1.getLastCellNum(); // Te devuelve el ndice de la ltima celda M?S 1 } catch (NullPointerException e) { numCell1 = 0; } try { numCell2 = fila2.getLastCellNum(); } catch (NullPointerException e) { numCell2 = 0; } int maxNumCells = numCell1 > numCell2 ? numCell1 : numCell2; for (int i = 0; i < maxNumCells; i++) { try { cell1 = fila1.getCell(i); } catch (NullPointerException | IllegalArgumentException ex) { cell1 = null; } try { cell2 = fila2.getCell(i); } catch (NullPointerException | IllegalArgumentException ex) { cell2 = null; } if (!comparaCelda(cell1, cell2, cache)) res = false; } return res; }
From source file:xmv.solutions.IT2JZ.Jira.Excel2TestcaseConverter.java
public List<JiraTestcase> parse() { // Reset first testcases = new ArrayList<JiraTestcase>(); // Check Excel File if (excelFile == null || !excelFile.testExcelFile()) { return null; }//from ww w. j av a 2s .c om try { // Get the workbook instance for XLS file Workbook workbook = excelFile.getWorkbook(); for (Sheet sheet : workbook) { String Sheetname = ""; try { // Take Sheet next sheet Sheetname = sheet.getSheetName(); } catch (Exception e) { // Problem with Excelfile break; } // Initiate TestSet String summary = null; String description = null; List<JiraTestcaseStep> steps = new ArrayList<JiraTestcaseStep>(); JiraTestcaseStep step = null; for (Row row : sheet) { // Omitt first line or empty ones if (row.getRowNum() == 0 || row == null || row.getLastCellNum() < 1) { continue; } try { // Scan Columns String A = row.getCell(0) != null ? row.getCell(0).getStringCellValue() : ""; String B = row.getCell(1) != null ? row.getCell(1).getStringCellValue() : ""; String C = row.getCell(2) != null ? row.getCell(2).getStringCellValue() : ""; String D = row.getCell(3) != null ? row.getCell(3).getStringCellValue() : ""; String E = row.getCell(4) != null ? row.getCell(4).getStringCellValue() : ""; String F = row.getCell(5) != null ? row.getCell(5).getStringCellValue() : ""; // if the First coulumn isn't empty, we start a new step if (!A.isEmpty()) { // finnish last testcase if we can, respctl all // attributes are ready if (summary != null && description != null && !steps.isEmpty()) { // Generate testcase and add to List testcases.add(new JiraTestcase(summary, description, steps)); // Reset summary = null; description = null; step = null; steps = new ArrayList<JiraTestcaseStep>(); } // Start new Testcase summary = parseMapping(summaryFM, A, B, C, D, E, F, Sheetname); description = parseMapping(descriptionFM, A, B, C, D, E, F, Sheetname); ; } step = new JiraTestcaseStep(); step.setStepName(parseMapping(testStepNameFM, A, B, C, D, E, F, Sheetname)); step.setTestData(parseMapping(testStepDataFM, A, B, C, D, E, F, Sheetname)); step.setExpectedResult(parseMapping(testStepExpectedResultFM, A, B, C, D, E, F, Sheetname)); steps.add(step); } catch (Exception e) { e.printStackTrace(); break; } } // Generate very last testcase and add to List if (summary != null && description != null && !steps.isEmpty()) { testcases.add(new JiraTestcase(summary, description, steps)); } } } catch (Exception e) { e.printStackTrace(); } return testcases; }