List of usage examples for org.apache.poi.ss.usermodel Workbook getSheet
Sheet getSheet(String name);
From source file:org.corpus_tools.peppermodules.spreadsheet.Spreadsheet2SaltMapper.java
License:Apache License
private void setDocMetaData(Workbook workbook) { Sheet metaSheet = null;//from w w w . jav a 2 s. co m // default ("Tabelle2"/ second sheet) if (getProps().getMetaSheet().equals("Tabelle2")) { if (workbook.getNumberOfSheets() > 1) { metaSheet = workbook.getSheetAt(1); } } else { // get corpus sheet by name metaSheet = workbook.getSheet(getProps().getCorpusSheet()); } if (metaSheet != null) { DataFormatter formatter = new DataFormatter(); // start with the second row of the table, since the first row holds // the name of each tier int currRow = 1; while (currRow < metaSheet.getPhysicalNumberOfRows()) { // iterate through all rows of the given meta informations Row row = metaSheet.getRow(currRow); Cell metaKey = row.getCell(0); Cell metaValue = row.getCell(1); if (metaKey != null && !metaKey.toString().isEmpty()) { if (metaValue != null && !metaValue.toString().isEmpty()) { if (getDocument().getMetaAnnotation(metaKey.toString()) == null) { getDocument().createMetaAnnotation(null, formatter.formatCellValue(metaKey), formatter.formatCellValue(metaValue)); } else { SpreadsheetImporter.logger .warn("A meta information with the name \"" + formatter.formatCellValue(metaKey) + "\" allready exists and will not be replaced."); } } else { SpreadsheetImporter.logger .warn("No value for the meta data: \"" + metaKey.toString() + "\" found."); } } else { if (metaValue != null && !metaValue.toString().isEmpty()) { SpreadsheetImporter.logger.warn( "No meta annotation name for the value \"" + metaValue.toString() + "\" found."); } } currRow++; } } }
From source file:org.cytoscape.tableimport.internal.task.ImportAttributeTableReaderTask.java
License:Open Source License
@Override public void run(TaskMonitor tm) throws Exception { tm.setTitle("Loading table data"); tm.setProgress(0.0);// w w w .j a v a 2 s . c om tm.setStatusMessage("Loading table..."); Workbook workbook = null; // Load Spreadsheet data for preview. if (fileType != null && (fileType.equalsIgnoreCase(SupportedFileType.EXCEL.getExtension()) || fileType.equalsIgnoreCase(SupportedFileType.OOXML.getExtension())) && workbook == null) { try { workbook = WorkbookFactory.create(is); } catch (InvalidFormatException e) { e.printStackTrace(); throw new IllegalArgumentException("Could not read Excel file. Maybe the file is broken?"); } finally { if (is != null) is.close(); } } if (this.fileType.equalsIgnoreCase(SupportedFileType.EXCEL.getExtension()) || this.fileType.equalsIgnoreCase(SupportedFileType.OOXML.getExtension())) { // Fixed bug# 1668, Only load data from the first sheet, ignore the rest sheets // UPDATE: From the user perspective it makes more sense to get the selected tab/sheet instead. String networkName = amp.getName(); if (networkName == null) networkName = workbook.getSheetName(0); final Sheet sheet = workbook.getSheet(networkName); if (sheet != null) { reader = new ExcelAttributeSheetReader(sheet, amp, serviceRegistrar); loadAnnotation(tm); } } else { try { reader = new DefaultAttributeTableReader(null, amp, this.is, serviceRegistrar); loadAnnotation(tm); } catch (Exception ioe) { tm.showMessage(TaskMonitor.Level.ERROR, "Unable to read table: " + ioe.getMessage()); } } }
From source file:org.cytoscape.tableimport.internal.task.ImportNetworkTableReaderTask.java
License:Open Source License
@Override public void run(TaskMonitor tm) throws Exception { tm.setTitle("Loading network from table"); tm.setProgress(0.0);//from www . jav a2 s .co m tm.setStatusMessage("Loading network..."); Workbook workbook = null; // Load Spreadsheet data for preview. if (fileType != null && (fileType.equalsIgnoreCase(SupportedFileType.EXCEL.getExtension()) || fileType.equalsIgnoreCase(SupportedFileType.OOXML.getExtension())) && workbook == null) { try { workbook = WorkbookFactory.create(is); } catch (InvalidFormatException e) { throw new IllegalArgumentException("Could not read Excel file. Maybe the file is broken?", e); } finally { if (is != null) is.close(); } } try { if (this.fileType.equalsIgnoreCase(SupportedFileType.EXCEL.getExtension()) || this.fileType.equalsIgnoreCase(SupportedFileType.OOXML.getExtension())) { String networkName = ntmp.getName(); if (networkName == null) networkName = workbook.getSheetName(0); final Sheet sheet = workbook.getSheet(networkName); reader = new ExcelNetworkSheetReader(networkName, sheet, ntmp, nMap, rootNetwork, serviceRegistrar); } else { reader = new NetworkTableReader(inputName, is, ntmp, nMap, rootNetwork, serviceRegistrar); } } catch (Exception ioe) { tm.showMessage(TaskMonitor.Level.ERROR, "Unable to read table: " + ioe.getMessage()); return; } loadNetwork(tm); tm.setProgress(1.0); }
From source file:org.cytoscape.tableimport.internal.task.LoadNetworkReaderTask.java
License:Open Source License
@Override public void run(final TaskMonitor tm) throws Exception { tm.setTitle("Loading network from table"); tm.setProgress(0.0);//from w w w . j a v a2 s .c om tm.setStatusMessage("Loading network..."); taskMonitor = tm; final List<String> attrNameList = new ArrayList<>(); int colCount; String[] attributeNames; final CyNetworkReaderManager networkReaderManager = serviceRegistrar .getService(CyNetworkReaderManager.class); if (is != null) netReader = networkReaderManager.getReader(is, inputName); if (netReader == null) netReader = networkReaderManager.getReader(uri, inputName); if (netReader instanceof CombineReaderAndMappingTask) { Workbook workbook = null; // Load Spreadsheet data for preview. if (fileType != null && (fileType.equalsIgnoreCase(SupportedFileType.EXCEL.getExtension()) || fileType.equalsIgnoreCase(SupportedFileType.OOXML.getExtension())) && workbook == null) { try { workbook = WorkbookFactory.create(new FileInputStream(tempFile)); } catch (InvalidFormatException e) { //e.printStackTrace(); throw new IllegalArgumentException("Could not read Excel file. Maybe the file is broken?", e); } finally { } } netReader = null; if (startLoadRow > 0) startLoadRow--; final int startLoadRowTemp = firstRowAsColumnNames ? 0 : startLoadRow; previewPanel.updatePreviewTable(workbook, fileType, tempFile.getAbsolutePath(), new FileInputStream(tempFile), delimiters.getSelectedValues(), null, startLoadRowTemp); colCount = previewPanel.getPreviewTable().getColumnModel().getColumnCount(); Object curName = null; if (firstRowAsColumnNames) { previewPanel.setFirstRowAsColumnNames(); startLoadRow++; } final SourceColumnSemantic[] types = previewPanel.getTypes(); for (int i = 0; i < colCount; i++) { curName = previewPanel.getPreviewTable().getColumnModel().getColumn(i).getHeaderValue(); if (attrNameList.contains(curName)) { int dupIndex = 0; for (int idx = 0; idx < attrNameList.size(); idx++) { if (curName.equals(attrNameList.get(idx))) { dupIndex = idx; break; } } if (!TypeUtil.allowsDuplicateName(ImportType.NETWORK_IMPORT, types[i], types[dupIndex])) { // TODO add message to user (Duplicate Column Name Found) return; } } if (curName == null) attrNameList.add("Column " + i); else attrNameList.add(curName.toString()); } attributeNames = attrNameList.toArray(new String[attrNameList.size()]); final SourceColumnSemantic[] typesCopy = Arrays.copyOf(types, types.length); final AttributeDataType[] dataTypes = previewPanel.getDataTypes(); final AttributeDataType[] dataTypesCopy = Arrays.copyOf(dataTypes, dataTypes.length); AttributeDataType[] tunableDataTypes = null; if (dataTypeList != null && !dataTypeList.trim().isEmpty()) tunableDataTypes = TypeUtil.parseDataTypeList(dataTypeList); if (tunableDataTypes != null && tunableDataTypes.length > 0) System.arraycopy(tunableDataTypes, 0, dataTypesCopy, 0, Math.min(tunableDataTypes.length, dataTypesCopy.length)); String[] listDelimiters = previewPanel.getListDelimiters(); if (listDelimiters == null || listDelimiters.length == 0) { listDelimiters = new String[dataTypes.length]; if (delimitersForDataList.getSelectedValue() != null) Arrays.fill(listDelimiters, delimitersForDataList.getSelectedValue()); } if (indexColumnSourceInteraction > 0) indexColumnSourceInteraction--; if (indexColumnTargetInteraction > 0) indexColumnTargetInteraction--; if (indexColumnTypeInteraction > 0) indexColumnTypeInteraction--; networkName = previewPanel.getSourceName(); ntmp = new NetworkTableMappingParameters(networkName, delimiters.getSelectedValues(), listDelimiters, attributeNames, dataTypesCopy, typesCopy, indexColumnSourceInteraction, indexColumnTargetInteraction, indexColumnTypeInteraction, defaultInteraction, startLoadRow, null); try { if (this.fileType.equalsIgnoreCase(SupportedFileType.EXCEL.getExtension()) || this.fileType.equalsIgnoreCase(SupportedFileType.OOXML.getExtension())) { final Sheet sheet = workbook.getSheet(networkName); reader = new ExcelNetworkSheetReader(networkName, sheet, ntmp, nMap, rootNetwork, serviceRegistrar); } else { networkName = this.inputName; reader = new NetworkTableReader(networkName, new FileInputStream(tempFile), ntmp, nMap, rootNetwork, serviceRegistrar); } } catch (Exception ioe) { tm.showMessage(TaskMonitor.Level.ERROR, "Unable to read network: " + ioe.getMessage()); return; } loadNetwork(tm); tm.setProgress(1.0); } else { networkName = this.inputName; insertTasksAfterCurrentTask(netReader); } }
From source file:org.cytoscape.tableimport.internal.task.LoadTableReaderTask.java
License:Open Source License
@Override public void run(final TaskMonitor tm) throws Exception { tm.setTitle("Loading table data"); tm.setProgress(0.0);//from w w w .ja v a 2 s. co m tm.setStatusMessage("Loading table..."); List<String> attrNameList = new ArrayList<>(); int colCount; String[] attributeNames; Workbook workbook = null; // Load Spreadsheet data for preview. try { if (fileType != null && (fileType.equalsIgnoreCase(SupportedFileType.EXCEL.getExtension()) || fileType.equalsIgnoreCase(SupportedFileType.OOXML.getExtension())) && workbook == null) { try { workbook = WorkbookFactory.create(isStart); } catch (InvalidFormatException e) { e.printStackTrace(); throw new IllegalArgumentException("Could not read Excel file. Maybe the file is broken?"); } finally { if (isStart != null) isStart.close(); } } } catch (Exception ioe) { tm.showMessage(TaskMonitor.Level.ERROR, "Unable to read table: " + ioe.getMessage()); return; } if (startLoadRow > 0) startLoadRow--; final int startLoadRowTemp = firstRowAsColumnNames ? 0 : startLoadRow; previewPanel.updatePreviewTable(workbook, fileType, inputName, isStart, delimiters.getSelectedValues(), null, startLoadRowTemp); colCount = previewPanel.getPreviewTable().getColumnModel().getColumnCount(); Object curName = null; if (firstRowAsColumnNames) { previewPanel.setFirstRowAsColumnNames(); startLoadRow++; } final String sourceName = previewPanel.getSourceName(); final SourceColumnSemantic[] types = previewPanel.getTypes(); for (int i = 0; i < colCount; i++) { curName = previewPanel.getPreviewTable().getColumnModel().getColumn(i).getHeaderValue(); if (attrNameList.contains(curName)) { int dupIndex = 0; for (int idx = 0; idx < attrNameList.size(); idx++) { if (curName.equals(attrNameList.get(idx))) { dupIndex = idx; break; } } if (!TypeUtil.allowsDuplicateName(ImportType.TABLE_IMPORT, types[i], types[dupIndex])) { //TODO add message to user return; } } if (curName == null) attrNameList.add("Column " + i); else attrNameList.add(curName.toString()); } attributeNames = attrNameList.toArray(new String[0]); final SourceColumnSemantic[] typesCopy = Arrays.copyOf(types, types.length); final AttributeDataType[] dataTypes = previewPanel.getDataTypes(); final AttributeDataType[] dataTypesCopy = Arrays.copyOf(dataTypes, dataTypes.length); AttributeDataType[] tunableDataTypes = null; if (dataTypeList != null && !dataTypeList.trim().isEmpty()) tunableDataTypes = TypeUtil.parseDataTypeList(dataTypeList); if (tunableDataTypes != null && tunableDataTypes.length > 0) System.arraycopy(tunableDataTypes, 0, dataTypesCopy, 0, Math.min(tunableDataTypes.length, dataTypesCopy.length)); String[] listDelimiters = previewPanel.getListDelimiters(); if (listDelimiters == null || listDelimiters.length == 0) { listDelimiters = new String[dataTypes.length]; if (delimitersForDataList.getSelectedValue() != null) Arrays.fill(listDelimiters, delimitersForDataList.getSelectedValue()); } if (keyColumnIndex > 0) keyColumnIndex--; amp = new AttributeMappingParameters(sourceName, delimiters.getSelectedValues(), listDelimiters, keyColumnIndex, attributeNames, dataTypesCopy, typesCopy, startLoadRow, null); if (this.fileType.equalsIgnoreCase(SupportedFileType.EXCEL.getExtension()) || this.fileType.equalsIgnoreCase(SupportedFileType.OOXML.getExtension())) { // Fixed bug# 1668, Only load data from the first sheet, ignore the rest sheets // UPDATE: From the user perspective it makes more sense to get the selected tab/sheet than the first one. final Sheet sheet = workbook.getSheet(sourceName); if (sheet != null) { reader = new ExcelAttributeSheetReader(sheet, amp, serviceRegistrar); loadAnnotation(tm); } } else { reader = new DefaultAttributeTableReader(null, amp, this.isEnd, serviceRegistrar); loadAnnotation(tm); } }
From source file:org.databene.formats.xls.XLSLineIterator.java
License:Open Source License
private static Sheet sheet(String uri, String sheetName) throws IOException, ParseException { try {/*from ww w .ja va2 s. c o m*/ Workbook workbook = WorkbookFactory.create(IOUtil.getInputStreamForURI(uri)); Sheet sheet = sheetName != null ? workbook.getSheet(sheetName) : workbook.getSheetAt(0); if (sheet == null) throw new IllegalArgumentException("Sheet '" + sheetName + "' not found in file " + uri); return sheet; } catch (InvalidFormatException e) { throw new ParseException("Error parsing sheet '" + sheetName + "' of " + uri, null); } }
From source file:org.databene.platform.xls.SingleSheetXLSEntityIterator.java
License:Open Source License
private static Sheet loadSheet(String uri, String sheetName) throws InvalidFormatException, IOException { Workbook workbook = WorkbookFactory.create(IOUtil.getInputStreamForURI(uri)); Sheet sheet = workbook.getSheet(sheetName); if (sheet == null) throw new ConfigurationError("Sheet '" + sheetName + "' not found in file " + uri); return sheet; }
From source file:org.datanucleus.store.excel.ExcelPersistenceHandler.java
License:Open Source License
/** * Method to insert the object into the datastore. * @param op ObjectProvider of the object */// w ww . j a v a 2s .c om public void insertObject(final ObjectProvider op) { // Check if read-only so update not permitted assertReadOnlyForUpdateOfObject(op); AbstractClassMetaData cmd = op.getClassMetaData(); ExecutionContext ec = op.getExecutionContext(); ManagedConnection mconn = storeMgr.getConnection(ec); try { long startTime = System.currentTimeMillis(); if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled()) { NucleusLogger.DATASTORE_PERSIST.debug( Localiser.msg("Excel.Insert.Start", op.getObjectAsPrintable(), op.getInternalObjectId())); } Workbook wb = (Workbook) mconn.getConnection(); if (!storeMgr.managesClass(cmd.getFullClassName())) { // Make sure schema exists, using this connection ((ExcelStoreManager) storeMgr).manageClasses(new String[] { cmd.getFullClassName() }, ec.getClassLoaderResolver(), wb); } Table table = ec.getStoreManager().getStoreDataForClass(cmd.getFullClassName()).getTable(); if (cmd.getIdentityType() == IdentityType.APPLICATION || cmd.getIdentityType() == IdentityType.DATASTORE) { // Enforce uniqueness of datastore rows try { locateObject(op); throw new NucleusUserException(Localiser.msg("Excel.Insert.ObjectWithIdAlreadyExists", op.getObjectAsPrintable(), op.getInternalObjectId())); } catch (NucleusObjectNotFoundException onfe) { // Do nothing since object with this id doesn't exist } } int[] fieldNumbers = cmd.getAllMemberPositions(); String sheetName = table.getName(); Sheet sheet = wb.getSheet(sheetName); int rowNum = 0; if (sheet == null) { // Sheet doesn't exist so create it sheet = wb.createSheet(sheetName); if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled()) { NucleusLogger.DATASTORE_PERSIST.debug( Localiser.msg("Excel.Insert.SheetCreated", op.getObjectAsPrintable(), sheetName)); } } else { // Find number of active rows in this sheet rowNum += ExcelUtils.getNumberOfRowsInSheetOfWorkbook(op, wb); } // Create the object in the datastore Row row = sheet.getRow(rowNum); if (row == null) { // No row present so create holder for the cells row = sheet.createRow(rowNum); } op.provideFields(fieldNumbers, new StoreFieldManager(op, row, true, table)); if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled()) { NucleusLogger.DATASTORE_PERSIST .debug(Localiser.msg("Excel.ExecutionTime", (System.currentTimeMillis() - startTime))); } if (ec.getStatistics() != null) { ec.getStatistics().incrementNumWrites(); ec.getStatistics().incrementInsertCount(); } if (cmd.getIdentityType() == IdentityType.DATASTORE) { // Set the datastore identity column value int idCellNum = table.getDatastoreIdColumn().getPosition(); Object key = IdentityUtils.getTargetKeyForDatastoreIdentity(op.getInternalObjectId()); Cell idCell = row.getCell(idCellNum); if (idCell == null) { idCell = row.createCell(idCellNum); } if (key instanceof String) { idCell.setCellValue(wb.getCreationHelper().createRichTextString((String) key)); } else { idCell.setCellValue(((Long) key).longValue()); } } VersionMetaData vermd = cmd.getVersionMetaDataForClass(); if (vermd != null) { // versioned object so set its version int verCellNum = table.getVersionColumn().getPosition(); Cell verCell = row.getCell(verCellNum); if (verCell == null) { verCell = row.createCell(verCellNum); } Object nextVersion = VersionHelper.getNextVersion(vermd.getVersionStrategy(), null); op.setTransactionalVersion(nextVersion); if (nextVersion instanceof Long) { if (NucleusLogger.DATASTORE.isDebugEnabled()) { NucleusLogger.DATASTORE.debug(Localiser.msg("Excel.Insert.ObjectPersistedWithVersion", op.getObjectAsPrintable(), op.getInternalObjectId(), "" + nextVersion)); } verCell.setCellValue((Long) nextVersion); } else if (nextVersion instanceof Timestamp) { if (NucleusLogger.DATASTORE.isDebugEnabled()) { NucleusLogger.DATASTORE.debug(Localiser.msg("Excel.Insert.ObjectPersistedWithVersion", op.getObjectAsPrintable(), op.getInternalObjectId(), "" + nextVersion)); } Date date = new Date(); date.setTime(((Timestamp) nextVersion).getTime()); verCell.setCellValue(date); } } else { if (NucleusLogger.DATASTORE.isDebugEnabled()) { NucleusLogger.DATASTORE.debug(Localiser.msg("Excel.Insert.ObjectPersisted", op.getObjectAsPrintable(), op.getInternalObjectId())); } } } finally { mconn.release(); } }
From source file:org.datanucleus.store.excel.ExcelSchemaHandler.java
License:Open Source License
@Override public void createSchemaForClasses(Set<String> classNames, Properties props, Object connection) { Workbook wb = (Workbook) connection; ManagedConnection mconn = null;//from w w w .j a va 2 s .c o m try { if (wb == null) { mconn = storeMgr.getConnection(-1); wb = (Workbook) mconn.getConnection(); } Iterator<String> classIter = classNames.iterator(); ClassLoaderResolver clr = storeMgr.getNucleusContext().getClassLoaderResolver(null); while (classIter.hasNext()) { String className = classIter.next(); AbstractClassMetaData cmd = storeMgr.getMetaDataManager().getMetaDataForClass(className, clr); if (cmd != null) { StoreData storeData = storeMgr.getStoreDataForClass(cmd.getFullClassName()); Table table = null; if (storeData != null) { table = storeData.getTable(); } else { table = new CompleteClassTable(storeMgr, cmd, null); } String sheetName = table.getName(); Sheet sheet = wb.getSheet(sheetName); if (sheet == null) { // Sheet doesn't exist so create it sheet = wb.createSheet(sheetName); if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled()) { NucleusLogger.DATASTORE_PERSIST.debug( Localiser.msg("Excel.SchemaCreate.Class", cmd.getFullClassName(), sheetName)); } // Create columns of sheet for (int i = 0; i < table.getNumberOfColumns(); i++) { // TODO Create header row } } } } } finally { if (mconn != null) { mconn.release(); } } }
From source file:org.datanucleus.store.excel.ExcelSchemaHandler.java
License:Open Source License
@Override public void deleteSchemaForClasses(Set<String> classNames, Properties props, Object connection) { Workbook wb = (Workbook) connection; ManagedConnection mconn = null;//w w w. jav a 2 s . c o m try { if (wb == null) { mconn = storeMgr.getConnection(-1); wb = (Workbook) mconn.getConnection(); } Iterator<String> classIter = classNames.iterator(); ClassLoaderResolver clr = storeMgr.getNucleusContext().getClassLoaderResolver(null); while (classIter.hasNext()) { String className = classIter.next(); AbstractClassMetaData cmd = storeMgr.getMetaDataManager().getMetaDataForClass(className, clr); if (cmd != null) { StoreData storeData = storeMgr.getStoreDataForClass(cmd.getFullClassName()); Table table = null; if (storeData != null) { table = storeData.getTable(); } else { table = new CompleteClassTable(storeMgr, cmd, null); } String sheetName = table.getName(); Sheet sheet = wb.getSheet(sheetName); if (sheet != null) { wb.removeSheetAt(wb.getSheetIndex(sheetName)); if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled()) { NucleusLogger.DATASTORE_PERSIST.debug( Localiser.msg("Excel.SchemaDelete.Class", cmd.getFullClassName(), sheetName)); } } } } } finally { if (mconn != null) { mconn.release(); } } }