List of usage examples for org.apache.poi.ss.usermodel Row getRowNum
int getRowNum();
From source file:de.bund.bfr.knime.pmm.common.XLSReader.java
License:Open Source License
public Map<String, KnimeTuple> getTimeSeriesTuples(File file, String sheet, Map<String, Object> columnMappings, String timeUnit, String concentrationUnit, String agentColumnName, Map<String, AgentXml> agentMappings, String matrixColumnName, Map<String, MatrixXml> matrixMappings, boolean preserveIds, List<Integer> usedIds) throws Exception { Workbook wb = getWorkbook(file);//w ww . ja v a 2 s .c o m Sheet s = wb.getSheet(sheet); warnings.clear(); evaluator = wb.getCreationHelper().createFormulaEvaluator(); if (s == null) { throw new Exception("Sheet not found"); } Map<String, KnimeTuple> tuples = new LinkedHashMap<>(); Map<String, Integer> columns = getColumns(s); Map<String, Integer> miscColumns = new LinkedHashMap<>(); Integer idColumn = null; Integer commentColumn = null; Integer timeColumn = null; Integer logcColumn = null; Integer stdDevColumn = null; Integer nMeasureColumn = null; Integer agentDetailsColumn = null; Integer matrixDetailsColumn = null; Integer agentColumn = null; Integer matrixColumn = null; String timeColumnName = null; String logcColumnName = null; String stdDevColumnName = null; String nMeasureColumnName = null; if (agentColumnName != null) { agentColumn = columns.get(agentColumnName); } if (matrixColumnName != null) { matrixColumn = columns.get(matrixColumnName); } for (String column : columns.keySet()) { if (columnMappings.containsKey(column)) { Object mapping = columnMappings.get(column); if (mapping instanceof MiscXml) { miscColumns.put(column, columns.get(column)); } else if (mapping.equals(ID_COLUMN)) { idColumn = columns.get(column); } else if (mapping.equals(MdInfoXml.ATT_COMMENT)) { commentColumn = columns.get(column); } else if (mapping.equals(AttributeUtilities.TIME)) { timeColumn = columns.get(column); timeColumnName = column; } else if (mapping.equals(AttributeUtilities.CONCENTRATION)) { logcColumn = columns.get(column); logcColumnName = column; } else if (mapping.equals(XLSReader.CONCENTRATION_STDDEV_COLUMN)) { stdDevColumn = columns.get(column); stdDevColumnName = column; } else if (mapping.equals(XLSReader.CONCENTRATION_MEASURE_NUMBER)) { nMeasureColumn = columns.get(column); nMeasureColumnName = column; } else if (mapping.equals(AttributeUtilities.AGENT_DETAILS)) { agentDetailsColumn = columns.get(column); } else if (mapping.equals(AttributeUtilities.MATRIX_DETAILS)) { matrixDetailsColumn = columns.get(column); } } } List<Integer> newIds = new ArrayList<>(); ListMultimap<String, Row> rowsById = LinkedListMultimap.create(); if (idColumn != null) { for (int i = 1; !isEndOfFile(s, i); i++) { Row row = s.getRow(i); Cell idCell = row.getCell(idColumn); if (hasData(idCell)) { rowsById.put(getData(idCell), row); } } } for (Map.Entry<String, List<Row>> entry : Multimaps.asMap(rowsById).entrySet()) { KnimeTuple tuple = new KnimeTuple(SchemaFactory.createDataSchema()); PmmXmlDoc timeSeriesXml = new PmmXmlDoc(); String idString = entry.getKey(); Row firstRow = entry.getValue().get(0); Cell commentCell = null; Cell agentDetailsCell = null; Cell matrixDetailsCell = null; Cell agentCell = null; Cell matrixCell = null; if (commentColumn != null) { commentCell = firstRow.getCell(commentColumn); } if (agentDetailsColumn != null) { agentDetailsCell = firstRow.getCell(agentDetailsColumn); } if (matrixDetailsColumn != null) { matrixDetailsCell = firstRow.getCell(matrixDetailsColumn); } if (agentColumn != null) { agentCell = firstRow.getCell(agentColumn); } if (matrixColumn != null) { matrixCell = firstRow.getCell(matrixColumn); } int id; if (preserveIds && !usedIds.isEmpty()) { id = usedIds.remove(0); } else { id = MathUtilities.getRandomNegativeInt(); } newIds.add(id); tuple = new KnimeTuple(SchemaFactory.createDataSchema()); tuple.setValue(TimeSeriesSchema.ATT_COMBASEID, idString); tuple.setValue(TimeSeriesSchema.ATT_CONDID, id); timeSeriesXml = new PmmXmlDoc(); PmmXmlDoc dataInfo = new PmmXmlDoc(); PmmXmlDoc agentXml = new PmmXmlDoc(); PmmXmlDoc matrixXml = new PmmXmlDoc(); if (commentCell != null) { dataInfo.add(new MdInfoXml(null, null, getData(commentCell), null, null)); } else { dataInfo.add(new MdInfoXml(null, null, null, null, null)); } if (hasData(agentCell) && agentMappings.get(getData(agentCell)) != null) { agentXml.add(agentMappings.get(getData(agentCell))); } else { agentXml.add(new AgentXml()); } if (hasData(matrixCell) && matrixMappings.get(getData(matrixCell)) != null) { matrixXml.add(matrixMappings.get(getData(matrixCell))); } else { matrixXml.add(new MatrixXml()); } if (hasData(agentDetailsCell)) { ((AgentXml) agentXml.get(0)).setDetail(getData(agentDetailsCell)); } if (hasData(matrixDetailsCell)) { ((MatrixXml) matrixXml.get(0)).setDetail(getData(matrixDetailsCell)); } tuple.setValue(TimeSeriesSchema.ATT_MDINFO, dataInfo); tuple.setValue(TimeSeriesSchema.ATT_AGENT, agentXml); tuple.setValue(TimeSeriesSchema.ATT_MATRIX, matrixXml); PmmXmlDoc miscXML = new PmmXmlDoc(); for (String column : miscColumns.keySet()) { MiscXml misc = (MiscXml) columnMappings.get(column); Cell cell = firstRow.getCell(miscColumns.get(column)); if (hasData(cell)) { try { misc.setValue(Double.parseDouble(getData(cell).replace(",", "."))); } catch (NumberFormatException e) { warnings.add(column + " value in row " + (firstRow.getRowNum() + 1) + " is not valid (" + getData(cell) + ")"); misc.setValue(null); } } else { misc.setValue(null); } misc.setOrigUnit(misc.getUnit()); miscXML.add(misc); } tuple.setValue(TimeSeriesSchema.ATT_MISC, miscXML); for (Row row : entry.getValue()) { Cell timeCell = null; Cell logcCell = null; Cell stdDevCell = null; Cell nMeasureCell = null; if (timeColumn != null) { timeCell = row.getCell(timeColumn); } if (logcColumn != null) { logcCell = row.getCell(logcColumn); } if (stdDevColumn != null) { stdDevCell = row.getCell(stdDevColumn); } if (nMeasureColumn != null) { nMeasureCell = row.getCell(nMeasureColumn); } Double time = null; Double logc = null; Double stdDev = null; Integer nMeasure = null; if (hasData(timeCell)) { try { time = Double.parseDouble(getData(timeCell).replace(",", ".")); } catch (NumberFormatException e) { warnings.add(timeColumnName + " value in row " + (row.getRowNum() + 1) + " is not valid (" + getData(timeCell) + ")"); } } else if (timeColumn != null) { warnings.add(timeColumnName + " value in row " + (row.getRowNum() + 1) + " is missing"); } if (hasData(logcCell)) { try { logc = Double.parseDouble(getData(logcCell).replace(",", ".")); } catch (NumberFormatException e) { warnings.add(logcColumnName + " value in row " + (row.getRowNum() + 1) + " is not valid (" + getData(logcCell) + ")"); } } else if (logcColumn != null) { warnings.add(logcColumnName + " value in row " + (row.getRowNum() + 1) + " is missing"); } if (hasData(stdDevCell)) { try { stdDev = Double.parseDouble(getData(stdDevCell).replace(",", ".")); } catch (NumberFormatException e) { warnings.add(stdDevColumnName + " value in row " + (row.getRowNum() + 1) + " is not valid (" + getData(stdDevCell) + ")"); } } else if (stdDevColumn != null) { warnings.add(stdDevColumnName + " value in row " + (row.getRowNum() + 1) + " is missing"); } if (hasData(nMeasureCell)) { try { String number = getData(nMeasureCell).replace(",", "."); if (number.contains(".")) { number = number.substring(0, number.indexOf(".")); } nMeasure = Integer.parseInt(number); } catch (NumberFormatException e) { warnings.add(nMeasureColumnName + " value in row " + (row.getRowNum() + 1) + " is not valid (" + getData(nMeasureCell) + ")"); } } else if (nMeasureColumn != null) { warnings.add(nMeasureColumnName + " value in row " + (row.getRowNum() + 1) + " is missing"); } for (String column : miscColumns.keySet()) { PmmXmlDoc misc = tuple.getPmmXml(TimeSeriesSchema.ATT_MISC); Cell cell = row.getCell(miscColumns.get(column)); if (hasData(cell)) { try { String param = ((MiscXml) columnMappings.get(column)).getName(); double value = Double.parseDouble(getData(cell).replace(",", ".")); if (!hasSameValue(param, value, misc)) { warnings.add("Variable conditions cannot be imported: " + "Only first value for " + column + " is used"); } } catch (NumberFormatException e) { } } } timeSeriesXml .add(new TimeSeriesXml(null, time, timeUnit, logc, concentrationUnit, stdDev, nMeasure)); } tuple.setValue(TimeSeriesSchema.ATT_TIMESERIES, timeSeriesXml); tuples.put(idString, tuple); } usedIds.clear(); usedIds.addAll(newIds); return tuples; }
From source file:de.enerko.reports2.engine.Report.java
License:Apache License
public List<CellDefinition> evaluateWorkbook() { final List<CellDefinition> rv = new ArrayList<CellDefinition>(); boolean reevaluate = false; if (workbook instanceof HSSFWorkbook) { try {//from www . j a v a2s .co m workbook.getCreationHelper().createFormulaEvaluator().evaluateAll(); } catch (Exception e) { reevaluate = true; } } final FormulaEvaluator formulaEvaluator = new HSSFFormulaEvaluator((HSSFWorkbook) workbook, IStabilityClassifier.TOTALLY_IMMUTABLE); formulaEvaluator.clearAllCachedResultValues(); for (int i = 0; i < workbook.getNumberOfSheets(); ++i) { final Sheet sheet = workbook.getSheetAt(i); for (Row row : sheet) { for (Cell cell : row) { if (reevaluate && cell.getCellType() == Cell.CELL_TYPE_FORMULA) { try { formulaEvaluator.evaluateFormulaCell(cell); } catch (Exception e) { ReportEngine.logger.log(Level.WARNING, String.format("Could not evaluate formula '%s' in cell %s on sheet '%s': %s", cell.getCellFormula(), CellReferenceHelper .getCellReference(cell.getColumnIndex(), row.getRowNum()), sheet.getSheetName(), e.getMessage())); } } final CellDefinition cellDefinition = IMPORTABLE_CELL_TYPES.containsKey( new Integer(cell.getCellType())) ? new CellDefinition(sheet.getSheetName(), cell) : null; if (cellDefinition != null) rv.add(cellDefinition); } } } return rv; }
From source file:de.fme.alfresco.repo.web.scripts.DeclarativeSpreadsheetWebScript.java
License:Open Source License
/** * Generates the spreadsheet, based on the properties in the header * and a callback for the body./* w ww. j a v a 2s.c o m*/ */ public void generateSpreadsheet(Object resource, String format, WebScriptRequest req, Status status, Map<String, Object> model) throws IOException { Pattern qnameMunger = Pattern.compile("([A-Z][a-z]+)([A-Z].*)"); // Build up the details of the header List<Pair<QName, Boolean>> propertyDetails = buildPropertiesForHeader(resource, format, req); String[] headings = new String[propertyDetails.size()]; String[] descriptions = new String[propertyDetails.size()]; boolean[] required = new boolean[propertyDetails.size()]; for (int i = 0; i < headings.length; i++) { Pair<QName, Boolean> property = propertyDetails.get(i); if (property == null || property.getFirst() == null) { headings[i] = ""; required[i] = false; } else { QName column = property.getFirst(); required[i] = property.getSecond(); // Ask the dictionary service nicely for the details PropertyDefinition pd = dictionaryService.getProperty(column); if (pd != null && pd.getTitle() != null) { // Use the friendly titles, which may even be localised! headings[i] = pd.getTitle(); descriptions[i] = pd.getDescription(); } else { // Nothing friendly found, try to munge the raw qname into // something we can show to a user... String raw = column.getLocalName(); raw = raw.substring(0, 1).toUpperCase() + raw.substring(1); Matcher m = qnameMunger.matcher(raw); if (m.matches()) { headings[i] = m.group(1) + " " + m.group(2); } else { headings[i] = raw; } } } } // Build a list of just the properties List<QName> properties = new ArrayList<QName>(propertyDetails.size()); for (Pair<QName, Boolean> p : propertyDetails) { QName qn = null; if (p != null) { qn = p.getFirst(); } properties.add(qn); } // Output if ("csv".equals(format)) { StringWriter sw = new StringWriter(); CSVPrinter csv = new CSVPrinter(sw, CSVStrategy.EXCEL_STRATEGY); csv.println(headings); populateBody(resource, csv, properties); model.put(MODEL_CSV, sw.toString()); } else { Workbook wb; if ("xlsx".equals(format)) { wb = new XSSFWorkbook(); // TODO Properties } else { wb = new HSSFWorkbook(); // TODO Properties } // Add our header row Sheet sheet = wb.createSheet("Export"); Row hr = sheet.createRow(0); try { sheet.createFreezePane(0, 1); } catch (IndexOutOfBoundsException e) { //https://issues.apache.org/bugzilla/show_bug.cgi?id=51431 & http://stackoverflow.com/questions/6469693/apache-poi-clearing-freeze-split-panes } Font fb = wb.createFont(); fb.setBoldweight(Font.BOLDWEIGHT_BOLD); Font fi = wb.createFont(); fi.setBoldweight(Font.BOLDWEIGHT_BOLD); fi.setItalic(true); CellStyle csReq = wb.createCellStyle(); csReq.setFont(fb); CellStyle csOpt = wb.createCellStyle(); csOpt.setFont(fi); // Populate the header Drawing draw = null; for (int i = 0; i < headings.length; i++) { Cell c = hr.createCell(i); c.setCellValue(headings[i]); if (required[i]) { c.setCellStyle(csReq); } else { c.setCellStyle(csOpt); } if (headings[i].length() == 0) { sheet.setColumnWidth(i, 3 * 250); } else { sheet.setColumnWidth(i, 18 * 250); } if (descriptions[i] != null && descriptions[i].length() > 0) { // Add a description for it too if (draw == null) { draw = sheet.createDrawingPatriarch(); } ClientAnchor ca = wb.getCreationHelper().createClientAnchor(); ca.setCol1(c.getColumnIndex()); ca.setCol2(c.getColumnIndex() + 1); ca.setRow1(hr.getRowNum()); ca.setRow2(hr.getRowNum() + 2); Comment cmt = draw.createCellComment(ca); cmt.setAuthor(""); cmt.setString(wb.getCreationHelper().createRichTextString(descriptions[i])); cmt.setVisible(false); c.setCellComment(cmt); } } // Have the contents populated populateBody(resource, wb, sheet, properties); // Save it for the template ByteArrayOutputStream baos = new ByteArrayOutputStream(); wb.write(baos); model.put(MODEL_EXCEL, baos.toByteArray()); } }
From source file:de.iteratec.iteraplan.businesslogic.exchange.elasticExcel.excelimport.EntityDataImporter.java
License:Open Source License
private boolean importEntity(SheetContext sheetContext, Row row) { if (!containsData(sheetContext, row)) { return false; }/*from w w w. j a va2s .c om*/ UniversalTypeExpression entityType = (UniversalTypeExpression) sheetContext.getExpression(); UniversalModelExpression instance = getInstance(entityType, row.getRowNum() - FIRST_DATA_ROW_NO); if (instance == null) { return false; } for (int col = 0; col < sheetContext.getColumnCount(); col++) { ColumnContext column = sheetContext.getColumns().get(col); FeatureExpression<?> featureExpression = column.getFeatureExpression(); Cell cell = row.getCell(col); if (BuiltinPrimitiveType.DURATION.equals(featureExpression.getType())) { if (pass == Pass.PRIMITIVES) { Cell endCell = row.getCell(col + 1); importRuntimePeriodExpression(instance, featureExpression, cell, endCell); } col++; } else if (cell != null) { // cell may be null if the value is not set and rows are not created by the template generator. importFeatureExpression(instance, featureExpression, cell); } } return true; }
From source file:de.iteratec.iteraplan.businesslogic.exchange.elasticExcel.excelimport.RelationDataImporter.java
License:Open Source License
/** * @param row/*from w ww.j a v a 2 s. com*/ * @param ferFrom * @param ferTo * * @return true if this method did an import, false if it hit an empty row. */ private boolean importRelation(Row row, SubstantialTypeExpression fromType, SubstantialTypeExpression toType, RelationshipEndExpression expr) { if (row == null || row.getCell(0) == null || ExcelUtils.isEmptyCell(row.getCell(0))) { return false; } String fromName = getName(row.getCell(0), fromType); String toName = getName(row.getCell(1), toType); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Relation: From {0}[{1}] to {2}[{3}] via {4}[{5}]", fromType.getPersistentName(), fromName, // toType.getPersistentName(), toName, // expr.getType().getPersistentName(), expr.getName()); } UniversalModelExpression fromInstance = model.findByName(fromType, fromName); UniversalModelExpression toInstance = model.findByName(toType, toName); if (fromInstance == null || toInstance == null) { logError("Sheet \"{0}\", row {1}: fromInstance {2} or toInstance {3} is null!", row.getSheet().getSheetName(), Integer.valueOf(row.getRowNum() + 1), fromInstance, toInstance); } else { LOGGER.debug("About to create relation: from {0} to {1}", fromInstance, toInstance); fromInstance.connect(expr, toInstance); } return true; }
From source file:de.iteratec.iteraplan.businesslogic.exchange.legacyExcel.exporter.ExportWorkbook.java
License:Open Source License
/** * Adds headers stored in <code>headers</code> to the current sheet. If required, a special width * for the corresponding column can be set by providing a value in <code>headersWidth</code> using * header as key.<br/>/*from w w w. j av a 2 s.c om*/ * <b>IMPORTANT</b>: Headers are added in the order provided in <code>headers</code>. * * @param headers * headers to be added */ public void addHeaders(int sheetId, List<ExcelSheet.Header> headers) { Sheet sheet = getSheetById(sheetId); Drawing drawing = sheet.createDrawingPatriarch(); CreationHelper factory = sheet.getWorkbook().getCreationHelper(); Row row = sheet.createRow(this.getCurrentRowOfSheet(sheet, 3)); int columnIndex = 0; for (ExcelSheet.Header header : headers) { int currColumnIndex = columnIndex; Cell cell = row.createCell(columnIndex); if (header.getDescription() != null) { ClientAnchor commentAnchor = factory.createClientAnchor(); //Sizing the comment 1x3 cells commentAnchor.setCol1(cell.getColumnIndex()); commentAnchor.setCol2(cell.getColumnIndex() + 1); commentAnchor.setRow1(row.getRowNum()); commentAnchor.setRow2(row.getRowNum() + 3); Comment comment = drawing.createCellComment(commentAnchor); RichTextString str = factory.createRichTextString(header.getDescription()); comment.setString(str); comment.setAuthor(""); cell.setCellComment(comment); } setCellValue(cell, header.getLabel(), getHeaderTableStyle()); Integer width = header.getWidth(); if (width != null) { sheet.setColumnWidth(currColumnIndex, width.intValue()); } columnIndex++; } LOGGER.debug("Added headers."); }
From source file:de.iteratec.iteraplan.businesslogic.exchange.legacyExcel.importer.ObjectRelatedPermissionsWorkbook.java
License:Open Source License
private List<ObjectRelatedPermissionsData> readContentFromSheet(List<Row> sheetContentRows, Map<String, Integer> headline, TypeOfBuildingBlock typeOfBuildingBlock) { final List<ObjectRelatedPermissionsData> result = Lists.newArrayList(); for (Row row : sheetContentRows) { LOGGER.debug(" " + row.getSheet().getSheetName() + ": Row " + row.getRowNum()); Map<String, Cell> rowContent = ExcelImportUtilities.readRow(row, headline); ObjectRelatedPermissionsData userPermissions = parseRow(rowContent, typeOfBuildingBlock, row.getRowNum() + 1);/*from w w w. j a v a 2 s.c o m*/ if (userPermissions != null) { result.add(userPermissions); } } return result; }
From source file:de.iteratec.iteraplan.businesslogic.exchange.legacyExcel.importer.sheets.SheetImporter.java
License:Open Source License
public void doImport(Sheet sheet, int contentRowOffset, final int headRowIndex, LandscapeData landscapeData) { Row headlineRow = sheet.getRow(headRowIndex); Map<String, Integer> buildingBlocksHeadline = getBuildingBlocksHeadline(headlineRow); Map<String, Integer> attributesHeadline = getAttributeHeadline(headlineRow); int currentContentRow = contentRowOffset; while (ExcelImportUtilities.hasNextRow(sheet, currentContentRow)) { LOGGER.debug(" " + sheet.getSheetName() + ": Row " + currentContentRow); Row row = sheet.getRow(currentContentRow); // can happen if a row was deleted (but not removed) in Excel -> return no data if (row != null) { Map<String, Cell> buildingBlocksRow = ExcelImportUtilities.readRow(row, buildingBlocksHeadline); Map<String, Cell> attributes = ExcelImportUtilities.readRow(row, attributesHeadline); final LandscapeRowData rowData = new LandscapeRowData(buildingBlocksRow, attributes); try { save(rowData, landscapeData); } catch (IteraplanBusinessException e) { LOGGER.warn(e);// www.jav a 2 s.c o m getProcessingLog().warn("Error importing row {0}. Skipping.", Integer.valueOf(row.getRowNum() + 1)); } } currentContentRow += 1; } }
From source file:de.iteratec.iteraplan.businesslogic.exchange.timeseriesExcel.importer.TimeseriesExcelImporter.java
License:Open Source License
private BuildingBlock getBuildingBlock(Row row, BuildingBlockService<BuildingBlock, Integer> bbService) { Cell cell = row.getCell(BB_COL_NO);//from w w w . j av a 2 s . c om if (ExcelUtils.isEmptyCell(cell)) { logError(ExcelUtils.getFullCellReference(row.getSheet(), new CellReference(row.getRowNum(), BB_COL_NO)), "No Building Block found."); return null; } String bbName = StringUtils.trim(ExcelUtils.getStringCellValue(cell)); List<BuildingBlock> bbList = bbService.findByNames(Collections.singleton(bbName)); if (bbList == null || bbList.isEmpty()) { logError(ExcelUtils.getFullCellReference(cell), "No Building Block named \"{0}\" found.", bbName); return null; } if (bbList.size() > 1) { LOGGER.error("More than one Building Block named \"{0}\" found.", bbName); throw new IteraplanTechnicalException(IteraplanErrorMessages.GENERAL_TECHNICAL_ERROR); } return bbList.get(0); }
From source file:de.iteratec.iteraplan.businesslogic.exchange.timeseriesExcel.importer.TimeseriesExcelImporter.java
License:Open Source License
private Date getDate(Row row) { Cell cell = row.getCell(DATE_COL_NO); if (ExcelUtils.isEmptyCell(cell)) { logError(ExcelUtils.getFullCellReference(row.getSheet(), new CellReference(row.getRowNum(), DATE_COL_NO)), "No date value found."); return null; }/* w w w .jav a 2s .c om*/ Object dateCellValue = ExcelUtils.getCellValue(cell, true); if (!(dateCellValue instanceof Date)) { logError(ExcelUtils.getFullCellReference(cell), "No date value found."); return null; } else { Date date = (Date) dateCellValue; if (now.isBefore(new LocalDate(date))) { logError(ExcelUtils.getFullCellReference(cell), "Date is after today. Only past dates or the present day are allowed for timeseries."); return null; } else { return date; } } }