List of usage examples for org.apache.poi.ss.usermodel Workbook getSheetName
String getSheetName(int sheet);
From source file:de.interactive_instruments.ShapeChange.SBVR.SbvrRuleLoader.java
License:Open Source License
/** * @param sbvrXls/*from ww w. j av a 2s . c o m*/ * @return mapping of schema package name to SBVR rules that apply to * classes in this schema * * <ul> * <li>key: class name</li> * <li>value: mapping of schema package name to SBVR rule info * <ul> * <li>key: schema package name ( * {@value #UNSPECIFIED_SCHEMA_PACKAGE_NAME} if no schema package * name has been provided)</li> * <li>value: list of SBVR rules that apply to classes in that * schema (the list is sorted according to lexical order on a) the * class name and b) the rule text)</li> * </ul> * </ul> */ private TreeMap<String, TreeMap<String, List<SbvrRuleInfo>>> parseSBVRRuleInfos(Workbook sbvrXls) { TreeMap<String, TreeMap<String, List<SbvrRuleInfo>>> rules = new TreeMap<String, TreeMap<String, List<SbvrRuleInfo>>>(); if (sbvrXls == null) return null; Sheet rulesSheet = null; for (int i = 0; i < sbvrXls.getNumberOfSheets(); i++) { String sheetName = sbvrXls.getSheetName(i); if (sheetName.equalsIgnoreCase("Constraints")) { rulesSheet = sbvrXls.getSheetAt(i); break; } } if (rulesSheet == null) { result.addError(this, 3); return null; } // read header row to determine which columns contain relevant // information Map<String, Integer> fieldIndexes = new HashMap<String, Integer>(); Row header = rulesSheet.getRow(rulesSheet.getFirstRowNum()); if (header == null) { result.addError(this, 4); return null; } boolean classNameFound = false; boolean commentsFound = false; boolean ruleNameFound = false; boolean ruleTextFound = false; boolean schemaPackageFound = false; for (short i = header.getFirstCellNum(); i < header.getLastCellNum(); i++) { Cell c = header.getCell(i, Row.RETURN_BLANK_AS_NULL); if (c == null) { // this is allowed } else { String value = c.getStringCellValue(); if (value.equalsIgnoreCase(SbvrRuleInfo.CLASS_COLUMN_NAME)) { fieldIndexes.put(SbvrRuleInfo.CLASS_COLUMN_NAME, (int) i); classNameFound = true; } else if (value.equalsIgnoreCase(SbvrRuleInfo.COMMENT_COLUMN_NAME)) { fieldIndexes.put(SbvrRuleInfo.COMMENT_COLUMN_NAME, (int) i); commentsFound = true; } else if (value.equalsIgnoreCase(SbvrRuleInfo.SCHEMA_PACKAGE_COLUMN_NAME)) { fieldIndexes.put(SbvrRuleInfo.SCHEMA_PACKAGE_COLUMN_NAME, (int) i); schemaPackageFound = true; } else if (value.equalsIgnoreCase(SbvrRuleInfo.RULE_TEXT_COLUMN_NAME)) { fieldIndexes.put(SbvrRuleInfo.RULE_TEXT_COLUMN_NAME, (int) i); ruleTextFound = true; } else if (value.equalsIgnoreCase(SbvrRuleInfo.RULE_NAME_COLUMN_NAME)) { fieldIndexes.put(SbvrRuleInfo.RULE_NAME_COLUMN_NAME, (int) i); ruleNameFound = true; } } } // if (fieldIndexes.size() != 5) { if (!ruleNameFound && !ruleTextFound) { // log message that required fields were not found result.addError(this, 5); return null; } /* * Read rule content */ for (int i = rulesSheet.getFirstRowNum() + 1; i <= rulesSheet.getLastRowNum(); i++) { Row r = rulesSheet.getRow(i); int rowNumber = i + 1; if (r == null) { // ignore empty rows continue; } SbvrRuleInfo sri = new SbvrRuleInfo(); // get rule name (required) Cell c = r.getCell(fieldIndexes.get(SbvrRuleInfo.RULE_NAME_COLUMN_NAME), Row.RETURN_BLANK_AS_NULL); if (c == null) { // log message result.addWarning(this, 6, "" + rowNumber); continue; } else { String cellValue = c.getStringCellValue(); if (cellValue != null) { if (cellValue.contains(":")) { sri.setName(cellValue.substring(cellValue.lastIndexOf(":") + 1)); } else { sri.setName(cellValue); } } } // get rule text (required) c = r.getCell(fieldIndexes.get(SbvrRuleInfo.RULE_TEXT_COLUMN_NAME), Row.RETURN_BLANK_AS_NULL); if (c == null) { // log message result.addWarning(this, 7, "" + rowNumber); continue; } else { sri.setText(c.getStringCellValue()); } // get comment (optional) if (commentsFound) { c = r.getCell(fieldIndexes.get(SbvrRuleInfo.COMMENT_COLUMN_NAME), Row.RETURN_BLANK_AS_NULL); if (c != null) { sri.setComment(c.getStringCellValue()); } } // get schema package (optional) if (schemaPackageFound) { c = r.getCell(fieldIndexes.get(SbvrRuleInfo.SCHEMA_PACKAGE_COLUMN_NAME), Row.RETURN_BLANK_AS_NULL); if (c == null) { sri.setSchemaPackageName(UNSPECIFIED_SCHEMA_PACKAGE_NAME); } else { sri.setSchemaPackageName(c.getStringCellValue()); } } /* * get class name (optional when loading from excel because later we * can still try parsing it from the rule text) */ if (classNameFound) { c = r.getCell(fieldIndexes.get(SbvrRuleInfo.CLASS_COLUMN_NAME), Row.RETURN_BLANK_AS_NULL); if (c == null) { /* * then after this we'll try to parse the class name from * the rule text */ } else { sri.setClassName(c.getStringCellValue()); } } if (sri.getClassName() == null) { /* * try parsing the main class name from the rule text */ result.addInfo(this, 10, sri.getName()); String mainClassName = parseClassNameFromRuleText(sri.getText()); if (mainClassName == null) { result.addWarning(this, 8, sri.getName()); continue; } else { sri.setClassName(mainClassName); } } List<SbvrRuleInfo> rulesList; TreeMap<String, List<SbvrRuleInfo>> rulesBySchemaPackageName; if (rules.containsKey(sri.getClassName())) { rulesBySchemaPackageName = rules.get(sri.getClassName()); if (rulesBySchemaPackageName.containsKey(sri.getSchemaPackageName())) { rulesList = rulesBySchemaPackageName.get(sri.getSchemaPackageName()); } else { rulesList = new ArrayList<SbvrRuleInfo>(); rulesBySchemaPackageName.put(sri.getSchemaPackageName(), rulesList); } } else { rulesBySchemaPackageName = new TreeMap<String, List<SbvrRuleInfo>>(); rules.put(sri.getClassName(), rulesBySchemaPackageName); rulesList = new ArrayList<SbvrRuleInfo>(); rulesBySchemaPackageName.put(sri.getSchemaPackageName(), rulesList); } rulesList.add(sri); } // now sort all lists contained in the map for (TreeMap<String, List<SbvrRuleInfo>> rulesBySchemaPackageName : rules.values()) { for (List<SbvrRuleInfo> rulesList : rulesBySchemaPackageName.values()) { Collections.sort(rulesList, new Comparator<SbvrRuleInfo>() { @Override public int compare(SbvrRuleInfo o1, SbvrRuleInfo o2) { int classNameComparison = o1.getClassName().compareTo(o2.getClassName()); if (classNameComparison != 0) { return classNameComparison; } else { return o1.getText().compareTo(o2.getText()); } } }); } } return rules; }
From source file:edu.ucsd.bioeng.coreplugin.tableImport.ui.ImportTextTableDialog.java
License:Open Source License
/** * Load from the data source.<br>//from w ww . j a va2 s. co m * * @param evt * @throws Exception */ private void importButtonActionPerformed(ActionEvent evt) throws Exception { if (checkDataSourceError() == false) return; boolean importAll = importAllCheckBox.isSelected(); /* * Get start line number. If "transfer" check box is true, then start * reading from the second line. */ int startLineNumber; final int spinnerNumber = Integer.parseInt(startRowSpinner.getValue().toString()); if (transferNameCheckBox.isSelected()) { startLineNumber = spinnerNumber; } else { startLineNumber = spinnerNumber - 1; } final String commentChar = commentLineTextField.getText(); /* * Get import flags */ final int colCount = previewPanel.getPreviewTable().getColumnModel().getColumnCount(); importFlag = new boolean[colCount]; for (int i = 0; i < colCount; i++) { importFlag[i] = ((AttributePreviewTableCellRenderer) previewPanel.getPreviewTable().getCellRenderer(0, i)).getImportFlag(i); } /* * Get Attribute Names */ final String[] attributeNames; final List<String> attrNameList = new ArrayList<String>(); Object curName = null; 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 (importFlag[i] && importFlag[dupIndex]) { final JLabel label = new JLabel("Duplicate Attribute Name Found: " + curName); label.setForeground(Color.RED); JOptionPane.showMessageDialog(this, label); return; } } if (curName == null) { attrNameList.add("Column " + i); } else { attrNameList.add(curName.toString()); } } attributeNames = attrNameList.toArray(new String[0]); /* * Get attribute data types */ // final byte[] attributeTypes = new byte[previewPanel.getPreviewTable() // .getColumnCount()]; final Byte[] test = previewPanel.getDataTypes(previewPanel.getSelectedSheetName()); final Byte[] attributeTypes = new Byte[test.length]; for (int i = 0; i < test.length; i++) { attributeTypes[i] = test[i]; } // for (int i = 0; i < attributeTypes.length; i++) { // attributeTypes[i] = attributeDataTypes.get(i); // } final List<Integer> aliasList = new ArrayList<Integer>(); String mappingAttribute = ID; if (dialogType != NETWORK_IMPORT) { /* * Get column indecies for alias */ JTable curTable = aliasTableMap.get(previewPanel.getSelectedSheetName()); if (curTable != null) { for (int i = 0; i < curTable.getModel().getRowCount(); i++) { if ((Boolean) curTable.getModel().getValueAt(i, 0) == true) { aliasList.add(i); } } } /* * Get mapping attribute */ mappingAttribute = mappingAttributeComboBox.getSelectedItem().toString(); } ObjectType objType = null; if (dialogType != NETWORK_IMPORT) { if (nodeRadioButton.isSelected()) { objType = NODE; } else if (edgeRadioButton.isSelected()) { objType = EDGE; } else { objType = NETWORK; } } /* * Switch readers based on the dialog type. */ switch (dialogType) { case SIMPLE_ATTRIBUTE_IMPORT: /* * Case 1: Attribute table import. */ // Extract URL from the text table. final URL source = new URL(targetDataSourceTextField.getText()); // Make sure primary key index is up-to-date. keyInFile = primaryKeyComboBox.getSelectedIndex(); // Build mapping parameter object. final AttributeMappingParameters mapping; final List<String> del; System.out.println("IsCytoscapeAttributeFile " + previewPanel.isCytoscapeAttributeFile(source)); if (previewPanel.isCytoscapeAttributeFile(source)) { del = new ArrayList<String>(); del.add(" += +"); } else { del = checkDelimiter(); } mapping = new AttributeMappingParameters(objType, del, listDelimiter, keyInFile, mappingAttribute, aliasList, attributeNames, attributeTypes, listDataTypes, importFlag, caseSensitive); if (source.toString().endsWith(SupportedFileType.EXCEL.getExtension()) || source.toString().endsWith(SupportedFileType.OOXML.getExtension())) { /* * Read one sheet at a time */ InputStream is = null; Workbook wb = null; try { is = source.openStream(); wb = WorkbookFactory.create(is); } finally { if (is != null) { is.close(); } } // Load all sheets in the table for (int i = 0; i < wb.getNumberOfSheets(); i++) { final Sheet sheet = wb.getSheetAt(i); loadAnnotation(new ExcelAttributeSheetReader(sheet, mapping, startLineNumber, importAll), source.toString()); } } else { loadAnnotation(new DefaultAttributeTableReader(source, mapping, startLineNumber, null, importAll), source.toString()); } break; case ONTOLOGY_AND_ANNOTATION_IMPORT: /* * Case 2: Import Ontology and its annotation. */ final String selectedOntologyName = ontologyComboBox.getSelectedItem().toString(); final String ontologySourceLocation = ontologyUrlMap.get(selectedOntologyName); /* * If selected ontology is not loaded, load it first. */ if (Cytoscape.getOntologyServer().getOntologyNames().contains(selectedOntologyName) == false) loadOntology(ontologySourceLocation, selectedOntologyName); /* * Now, load & map annotation. */ final String annotationSource = annotationUrlMap.get(annotationComboBox.getSelectedItem()); final URL annotationSourceUrl = new URL(annotationSource); if (previewPanel.getFileType() == FileTypes.GENE_ASSOCIATION_FILE) { /* * This is a Gene Association file. */ GeneAssociationReader gaReader = null; keyInFile = this.primaryKeyComboBox.getSelectedIndex(); InputStream is = null; try { is = URLUtil.getInputStream(annotationSourceUrl); gaReader = new GeneAssociationReader(selectedOntologyName, is, mappingAttribute, importAll, keyInFile, caseSensitive); } catch (Exception e) { if (is != null) { is.close(); } throw e; } loadGeneAssociation(gaReader, selectedOntologyName, annotationSource); } else { /* * This is a custom annotation file. */ final int ontologyIndex = ontologyInAnnotationComboBox.getSelectedIndex(); final AttributeAndOntologyMappingParameters aoMapping = new AttributeAndOntologyMappingParameters( objType, checkDelimiter(), listDelimiter, keyInFile, mappingAttribute, aliasList, attributeNames, attributeTypes, listDataTypes, importFlag, ontologyIndex, selectedOntologyName, caseSensitive); final OntologyAnnotationReader oaReader = new OntologyAnnotationReader(annotationSourceUrl, aoMapping, commentChar, startLineNumber); loadAnnotation(oaReader, annotationSource); } break; case NETWORK_IMPORT: /* * Case 3: read as network table (Network + Edge Attributes) */ // Extract URL from the text table. /* * Now multiple files are supported. */ URL[] sources = new URL[inputFiles.length]; for (int i = 0; i < sources.length; i++) { sources[i] = inputFiles[i].toURI().toURL(); } //final URL networkSource = new URL(targetDataSourceTextField.getText()); final int sourceColumnIndex = networkImportPanel.getSourceIndex(); final int targetColumnIndex = networkImportPanel.getTargetIndex(); final String defaultInteraction = defaultInteractionTextField.getText(); final int interactionColumnIndex = networkImportPanel.getInteractionIndex(); final NetworkTableMappingParameters nmp = new NetworkTableMappingParameters(checkDelimiter(), listDelimiter, attributeNames, attributeTypes, null, importFlag, sourceColumnIndex, targetColumnIndex, interactionColumnIndex, defaultInteraction); NetworkTableReader reader; String networkName; boolean multi = true; if (sources.length == 1) multi = false; for (int i = 0; i < sources.length; i++) { if (sources[i].toString().endsWith(SupportedFileType.EXCEL.getExtension()) || sources[i].toString().endsWith(SupportedFileType.OOXML.getExtension())) { // Extract name from the sheet name. InputStream is = null; Workbook wb = null; try { is = sources[i].openStream(); wb = WorkbookFactory.create(is); } finally { if (is != null) { is.close(); } } Sheet sheet = wb.getSheetAt(0); networkName = wb.getSheetName(0); reader = new ExcelNetworkSheetReader(networkName, sheet, nmp, startLineNumber); } else { // Get name from URL. if ((commentChar != null) && (commentChar.length() != 0) && transferNameCheckBox.isSelected()) { startLineNumber++; } final String[] parts = sources[i].toString().split("/"); networkName = parts[parts.length - 1]; reader = new NetworkTableReader(networkName, sources[i], nmp, startLineNumber, commentChar); } loadNetwork(networkName, reader, sources[i], multi); } if (multi) { StringBuilder builder = new StringBuilder(); builder.append("The following networks are loaded:\n\n"); for (File f : inputFiles) { builder.append(f.getName() + "\n"); } JOptionPane.showMessageDialog(this, builder.toString(), "Multiple Networks Loaded", JOptionPane.INFORMATION_MESSAGE); } break; default: return; } Cytoscape.firePropertyChange(Cytoscape.ATTRIBUTES_CHANGED, null, null); dispose(); }
From source file:edu.ucsd.bioeng.coreplugin.tableImport.ui.PreviewTablePanel.java
License:Open Source License
/** * Load file and show preview.//from ww w. ja v a2 s . c o m * * @param sourceURL * @param delimiters * @param renderer * renderer for this table. Can be null. * @param size * @param commentLineChar * TODO * @param startLine * TODO * @throws IOException */ public void setPreviewTable(URL sourceURL, List<String> delimiters, TableCellRenderer renderer, int size, final String commentLineChar, final int startLine) throws IOException { TableCellRenderer curRenderer = renderer; if ((commentLineChar != null) && (commentLineChar.trim().length() != 0)) this.commentChar = commentLineChar; else this.commentChar = null; /* * If rendrer is null, create default one. */ if (curRenderer == null) { curRenderer = new AttributePreviewTableCellRenderer(0, new ArrayList<Integer>(), AttributePreviewTableCellRenderer.PARAMETER_NOT_EXIST, AttributePreviewTableCellRenderer.PARAMETER_NOT_EXIST, null, TextFileDelimiters.PIPE.toString()); } /* * Reset current state */ for (int i = 0; i < tableTabbedPane.getTabCount(); i++) tableTabbedPane.removeTabAt(i); previewTables = new HashMap<String, JTable>(); TableModel newModel; fileTypeLabel.setVisible(true); if (sourceURL.toString().endsWith(SupportedFileType.EXCEL.getExtension()) || sourceURL.toString().endsWith(SupportedFileType.OOXML.getExtension())) { fileTypeLabel.setIcon(SPREADSHEET_ICON.getIcon()); fileTypeLabel.setText("Excel" + '\u2122' + " Workbook"); InputStream is = null; final Workbook wb; try { is = sourceURL.openStream(); wb = 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 (wb.getNumberOfSheets() == 0) throw new IllegalStateException("No sheet found in the workbook."); /* * Load each sheet in the workbook. */ logger.debug("# of Sheets = " + wb.getNumberOfSheets()); Sheet sheet = wb.getSheetAt(0); logger.debug("Sheet name = " + wb.getSheetName(0) + ", ROW = " + sheet.rowIterator().hasNext()); newModel = parseExcel(sourceURL, size, curRenderer, sheet, startLine); if (newModel.getRowCount() == 0) throw new IllegalStateException("No data found in the Excel sheet."); DataTypeUtil.guessTypes(newModel, wb.getSheetName(0), dataTypeMap); listDataTypeMap.put(wb.getSheetName(0), initListDataTypes(newModel)); addTableTab(newModel, wb.getSheetName(0), curRenderer); } else { if (isCytoscapeAttributeFile(sourceURL)) { fileTypeLabel.setText("Cytoscape Attribute File"); fileTypeLabel.setIcon(new ImageIcon(Cytoscape.class.getResource("images/icon48.png"))); newModel = parseText(sourceURL, size, curRenderer, null, 1); } else { fileTypeLabel.setText("Text File"); fileTypeLabel.setIcon(TEXT_FILE_ICON.getIcon()); newModel = parseText(sourceURL, size, curRenderer, delimiters, startLine); } String[] urlParts = sourceURL.toString().split("/"); final String tabName = urlParts[urlParts.length - 1]; DataTypeUtil.guessTypes(newModel, tabName, dataTypeMap); listDataTypeMap.put(tabName, initListDataTypes(newModel)); addTableTab(newModel, tabName, curRenderer); } if (getFileType() == FileTypes.GENE_ASSOCIATION_FILE) { fileTypeLabel.setText("Gene Association"); fileTypeLabel.setToolTipText("This is a fixed-format Gene Association file."); } loadFlag = true; }
From source file:egovframework.rte.fdl.excel.EgovExcelServiceTest.java
License:Apache License
/** * [Flow #-1] ? ? : ?? ?/*from ww w. j av a 2s .c o m*/ */ @Test public void testWriteExcelFile() throws Exception { try { LOGGER.debug("testWriteExcelFile start...."); String sheetName1 = "first sheet"; String sheetName2 = "second sheet"; StringBuffer sb = new StringBuffer(); sb.append(fileLocation).append("/").append("testWriteExcelFile.xls"); // delete file if (EgovFileUtil.isExistsFile(sb.toString())) { EgovFileUtil.delete(new File(sb.toString())); LOGGER.debug("Delete file...." + sb.toString()); } Workbook wb = new HSSFWorkbook(); wb.createSheet(sheetName1); wb.createSheet(sheetName2); wb.createSheet(); // ? ? Workbook tmp = excelService.createWorkbook(wb, sb.toString()); // ? ? assertTrue(EgovFileUtil.isExistsFile(sb.toString())); // ? Sheet ? ? assertEquals(sheetName1, tmp.getSheetName(0)); assertEquals(sheetName2, tmp.getSheetName(1)); } catch (Exception e) { LOGGER.error(e.toString()); throw new Exception(e); } finally { LOGGER.debug("testWriteExcelFile end...."); } }
From source file:egovframework.rte.fdl.excel.EgovExcelXSSFServiceTest.java
License:Apache License
/** * [Flow #-1] ? ? : ?? ?/*w ww.j av a 2s . com*/ */ @Test public void testWriteExcelFile() throws Exception { try { LOGGER.debug("testWriteExcelFile start...."); String sheetName1 = "first sheet"; String sheetName2 = "second sheet"; StringBuffer sb = new StringBuffer(); sb.append(fileLocation).append("/").append("testWriteExcelFile.xlsx"); // delete file if (EgovFileUtil.isExistsFile(sb.toString())) { EgovFileUtil.delete(new File(sb.toString())); LOGGER.debug("Delete file....{}", sb.toString()); } Workbook wb = new XSSFWorkbook(); wb.createSheet(sheetName1); wb.createSheet(sheetName2); wb.createSheet(); // ? ? Workbook tmp = excelService.createWorkbook(wb, sb.toString()); // ? ? assertTrue(EgovFileUtil.isExistsFile(sb.toString())); // ? Sheet ? ? assertEquals(sheetName1, tmp.getSheetName(0)); assertEquals(sheetName2, tmp.getSheetName(1)); } catch (Exception e) { LOGGER.error(e.toString()); throw new Exception(e); } finally { LOGGER.debug("testWriteExcelFile end...."); } }
From source file:fi.hsl.parkandride.itest.AbstractReportingITest.java
License:EUPL
protected List<String> getSheetNames(Workbook workbook) { return IntStream.range(0, workbook.getNumberOfSheets()).mapToObj(i -> workbook.getSheetName(i)) .collect(toList());//from ww w . ja va 2 s . co m }
From source file:fll.util.ExcelCellReader.java
License:Open Source License
/** * Get the names of all sheets in the specified stream. * /*from w w w . ja va 2s .c om*/ * @throws IOException * @throws InvalidFormatException */ public static List<String> getAllSheetNames(final InputStream stream) throws InvalidFormatException, IOException { final List<String> sheetNames = new LinkedList<String>(); final Workbook workbook = createWorkbook(stream); final int numSheets = workbook.getNumberOfSheets(); for (int i = 0; i < numSheets; ++i) { sheetNames.add(workbook.getSheetName(i)); } return sheetNames; }
From source file:info.informationsea.java.excel2csv.Converter.java
License:Open Source License
private void doConvertAllSheets(List<File> inputFiles, File outputFile) throws Exception { Workbook workbook;/* w w w . j a v a 2s . c om*/ if (outputFile.isFile() && outputFile.length() > 512) { switch (Utilities.suggestFileTypeFromName(outputFile.getName())) { case FILETYPE_XLS: case FILETYPE_XLSX: workbook = WorkbookFactory.create(outputFile); break; default: throw new IllegalArgumentException("Output file format should be Excel format"); } } else { switch (Utilities.suggestFileTypeFromName(outputFile.getName())) { case FILETYPE_XLS: workbook = new HSSFWorkbook(); break; case FILETYPE_XLSX: if (largeExcelMode) workbook = new SXSSFWorkbook(); else workbook = new XSSFWorkbook(); break; default: throw new IllegalArgumentException("Output file format should be Excel format"); } } if (largeExcelMode && !(workbook instanceof SXSSFWorkbook)) { log.warn("Streaming output mode is disabled"); } //log.info("workbook: {}", workbook.getClass()); for (File oneInput : inputFiles) { switch (Utilities.suggestFileTypeFromName(oneInput.getName())) { case FILETYPE_XLSX: case FILETYPE_XLS: { Workbook inputWorkbook = WorkbookFactory.create(oneInput); int sheetNum = inputWorkbook.getNumberOfSheets(); for (int i = 0; i < sheetNum; i++) { try (TableReader reader = new ExcelSheetReader(inputWorkbook.getSheetAt(i))) { ExcelSheetWriter sheetWriter = new ExcelSheetWriter( Utilities.createUniqueNameSheetForWorkbook(workbook, inputWorkbook.getSheetName(i), overwriteSheet)); sheetWriter.setPrettyTable(prettyTable); try (TableWriter tableWriter = new FilteredWriter(sheetWriter, convertCellTypes, fistCount)) { Utilities.copyTable(reader, tableWriter, useHeader); } } } break; } default: { try (TableReader reader = Utilities.openReader(oneInput, inputSheetIndex, inputSheetName)) { ExcelSheetWriter sheetWriter = new ExcelSheetWriter(Utilities .createUniqueNameSheetForWorkbook(workbook, oneInput.getName(), overwriteSheet)); sheetWriter.setPrettyTable(prettyTable); try (TableWriter tableWriter = new FilteredWriter(sheetWriter, convertCellTypes, fistCount)) { Utilities.copyTable(reader, tableWriter, useHeader); } } break; } } } workbook.write(new FileOutputStream(outputFile)); }
From source file:info.informationsea.java.excel2csv.ConverterTest.java
License:Open Source License
@Test public void testDoConvert4() throws Exception { Path temporaryOutput = Files.createTempFile("excel2csv", ".xlsx"); Converter.builder().copyAllSheets(false).outputSheetName("iris").build().doConvert( Collections.singletonList(new File(temporaryDirectory.toFile(), "multisheet.xls")), temporaryOutput.toFile());/*from www.ja v a 2 s . c om*/ Workbook workbook = WorkbookFactory.create(temporaryOutput.toFile()); Assert.assertEquals(1, workbook.getNumberOfSheets()); for (String one : new String[] { "iris" }) { log.info("Sheet name: {}", workbook.getSheetName(0)); try (TableReader reader = new ExcelSheetReader(workbook.getSheet(one))) { Excel2CSVTest.assertObjects(reference.get(one), reader.readAll()); } } }
From source file:info.informationsea.java.excel2csv.Excel2CSVTest.java
License:Open Source License
@Test public void testMultiSheet() throws Exception { Path outputFile = Files.createTempFile("outputTest", ".xlsx"); new Excel2CSV().run(new String[] { sampleInput[0].toString(), outputFile.toString() }); new Excel2CSV().run(new String[] { sampleInput[1].toString(), outputFile.toString() }); new Excel2CSV().run(new String[] { sampleInput[0].toString(), outputFile.toString() }); try (FileInputStream inputStream = new FileInputStream(outputFile.toFile())) { Workbook workbook = new XSSFWorkbook(inputStream); for (int i = 0; i < workbook.getNumberOfSheets(); i++) { log.info("sheet {}", workbook.getSheetName(i)); }//ww w . j a va 2 s .c om } for (int i = 0; i < 3; i++) { try (TableReader tableReader = Utilities.openReader(outputFile.toFile(), i, null)) { assertObjects(expectedData, tableReader.readAll()); } } try (TableReader tableReader = Utilities.openReader(outputFile.toFile(), 10, sampleInput[0].getFileName().toString())) { assertObjects(expectedData, tableReader.readAll()); } try (TableReader tableReader = Utilities.openReader(outputFile.toFile(), 10, sampleInput[1].getFileName().toString())) { assertObjects(expectedData, tableReader.readAll()); } try (TableReader tableReader = Utilities.openReader(outputFile.toFile(), 10, sampleInput[0].getFileName().toString() + "-1")) { assertObjects(expectedData, tableReader.readAll()); } }