Example usage for org.apache.poi.ss.usermodel Workbook getNumberOfSheets

List of usage examples for org.apache.poi.ss.usermodel Workbook getNumberOfSheets

Introduction

In this page you can find the example usage for org.apache.poi.ss.usermodel Workbook getNumberOfSheets.

Prototype

int getNumberOfSheets();

Source Link

Document

Get the number of spreadsheets in the workbook

Usage

From source file:CellStyleDetails.java

License:Apache License

public static void main(String[] args) throws Exception {
    if (args.length == 0) {
        throw new IllegalArgumentException("Filename must be given");
    }/*from   w ww.  ja  va2s  .c o m*/

    Workbook wb = WorkbookFactory.create(new File(args[0]));
    DataFormatter formatter = new DataFormatter();

    for (int sn = 0; sn < wb.getNumberOfSheets(); sn++) {
        Sheet sheet = wb.getSheetAt(sn);
        System.out.println("Sheet #" + sn + " : " + sheet.getSheetName());

        for (Row row : sheet) {
            System.out.println("  Row " + row.getRowNum());

            for (Cell cell : row) {
                CellReference ref = new CellReference(cell);
                System.out.print("    " + ref.formatAsString());
                System.out.print(" (" + cell.getColumnIndex() + ") ");

                CellStyle style = cell.getCellStyle();
                System.out.print("Format=" + style.getDataFormatString() + " ");
                System.out.print("FG=" + renderColor(style.getFillForegroundColorColor()) + " ");
                System.out.print("BG=" + renderColor(style.getFillBackgroundColorColor()) + " ");

                Font font = wb.getFontAt(style.getFontIndex());
                System.out.print("Font=" + font.getFontName() + " ");
                System.out.print("FontColor=");
                if (font instanceof HSSFFont) {
                    System.out.print(renderColor(((HSSFFont) font).getHSSFColor((HSSFWorkbook) wb)));
                }
                if (font instanceof XSSFFont) {
                    System.out.print(renderColor(((XSSFFont) font).getXSSFColor()));
                }

                System.out.println();
                System.out.println("        " + formatter.formatCellValue(cell));
            }
        }

        System.out.println();
    }
}

From source file:adams.data.io.input.ExcelSpreadSheetReader.java

License:Open Source License

/**
 * Reads the spreadsheet content from the specified file.
 *
 * @param in      the input stream to read from
 * @return      the spreadsheets or null in case of an error
 *///from   w  w  w  .  ja  va2  s.co  m
@Override
protected List<SpreadSheet> doReadRange(InputStream in) {
    List<SpreadSheet> result;
    int[] indices;
    Workbook workbook;
    Sheet sheet;
    SpreadSheet spsheet;
    Row exRow;
    Cell exCell;
    adams.data.spreadsheet.Row spRow;
    int i;
    int n;
    int cellType;
    DateFormat dformat;
    boolean numeric;
    int dataRowStart;
    int firstRow;
    int lastRow;
    List<String> header;

    result = new ArrayList<>();

    workbook = null;
    dformat = DateUtils.getTimestampFormatter();
    try {
        workbook = WorkbookFactory.create(in);
        m_SheetRange.setMax(workbook.getNumberOfSheets());
        indices = m_SheetRange.getIntIndices();
        firstRow = m_FirstRow - 1;
        dataRowStart = getNoHeader() ? firstRow : firstRow + 1;
        for (int index : indices) {
            if (m_Stopped)
                break;

            spsheet = m_SpreadSheetType.newInstance();
            spsheet.setDataRowClass(m_DataRowType.getClass());
            result.add(spsheet);

            if (isLoggingEnabled())
                getLogger().info("sheet: " + (index + 1));

            sheet = workbook.getSheetAt(index);
            if (sheet.getLastRowNum() == 0) {
                getLogger().severe("No rows in sheet #" + index);
                return null;
            }
            spsheet.setName(sheet.getSheetName());

            // header
            if (isLoggingEnabled())
                getLogger().info("header row");
            exRow = sheet.getRow(firstRow);
            if (exRow == null) {
                getLogger().warning("No data in sheet #" + (index + 1) + "?");
            } else if (exRow != null) {
                spRow = spsheet.getHeaderRow();
                m_TextColumns.setMax(exRow.getLastCellNum());
                if (getNoHeader()) {
                    header = SpreadSheetUtils.createHeader(exRow.getLastCellNum(), m_CustomColumnHeaders);
                    for (i = 0; i < header.size(); i++)
                        spRow.addCell("" + (i + 1)).setContent(header.get(i));
                } else {
                    if (!m_CustomColumnHeaders.trim().isEmpty()) {
                        header = SpreadSheetUtils.createHeader(exRow.getLastCellNum(), m_CustomColumnHeaders);
                        for (i = 0; i < header.size(); i++)
                            spRow.addCell("" + (i + 1)).setContent(header.get(i));
                    } else {
                        for (i = 0; i < exRow.getLastCellNum(); i++) {
                            if (m_Stopped)
                                break;
                            exCell = exRow.getCell(i);
                            if (exCell == null) {
                                spRow.addCell("" + (i + 1)).setMissing();
                                continue;
                            }
                            numeric = !m_TextColumns.isInRange(i);
                            switch (exCell.getCellType()) {
                            case Cell.CELL_TYPE_BLANK:
                            case Cell.CELL_TYPE_ERROR:
                                spRow.addCell("" + (i + 1)).setContent("column-" + (i + 1));
                                break;
                            case Cell.CELL_TYPE_NUMERIC:
                                if (HSSFDateUtil.isCellDateFormatted(exCell))
                                    spRow.addCell("" + (i + 1)).setContent(new DateTime(
                                            HSSFDateUtil.getJavaDate(exCell.getNumericCellValue())));
                                else if (numeric)
                                    spRow.addCell("" + (i + 1)).setContent(exCell.getNumericCellValue());
                                else
                                    spRow.addCell("" + (i + 1)).setContentAsString(numericToString(exCell));
                                break;
                            default:
                                spRow.addCell("" + (i + 1)).setContentAsString(exCell.getStringCellValue());
                            }
                        }
                    }
                }
            }

            // data
            if (spsheet.getColumnCount() > 0) {
                if (m_NumRows < 1)
                    lastRow = sheet.getLastRowNum();
                else
                    lastRow = Math.min(firstRow + m_NumRows - 1, sheet.getLastRowNum());
                for (i = dataRowStart; i <= lastRow; i++) {
                    if (m_Stopped)
                        break;
                    if (isLoggingEnabled())
                        getLogger().info("data row: " + (i + 1));
                    spRow = spsheet.addRow("" + spsheet.getRowCount());
                    exRow = sheet.getRow(i);
                    if (exRow == null)
                        continue;
                    for (n = 0; n < exRow.getLastCellNum(); n++) {
                        // too few columns in header?
                        if ((n >= spsheet.getHeaderRow().getCellCount()) && m_AutoExtendHeader)
                            spsheet.insertColumn(spsheet.getColumnCount(), "");

                        m_TextColumns.setMax(spsheet.getHeaderRow().getCellCount());
                        exCell = exRow.getCell(n);
                        if (exCell == null) {
                            spRow.addCell(n).setMissing();
                            continue;
                        }
                        cellType = exCell.getCellType();
                        if (cellType == Cell.CELL_TYPE_FORMULA)
                            cellType = exCell.getCachedFormulaResultType();
                        numeric = !m_TextColumns.isInRange(n);
                        switch (cellType) {
                        case Cell.CELL_TYPE_BLANK:
                        case Cell.CELL_TYPE_ERROR:
                            if (m_MissingValue.isEmpty())
                                spRow.addCell(n).setMissing();
                            else
                                spRow.addCell(n).setContent("");
                            break;
                        case Cell.CELL_TYPE_NUMERIC:
                            if (HSSFDateUtil.isCellDateFormatted(exCell))
                                spRow.addCell(n).setContent(
                                        dformat.format(HSSFDateUtil.getJavaDate(exCell.getNumericCellValue())));
                            else if (numeric)
                                spRow.addCell(n).setContent(exCell.getNumericCellValue());
                            else
                                spRow.addCell(n).setContentAsString(numericToString(exCell));
                            break;
                        default:
                            if (m_MissingValue.isMatch(exCell.getStringCellValue()))
                                spRow.addCell(n).setMissing();
                            else
                                spRow.addCell(n).setContentAsString(exCell.getStringCellValue());
                        }
                    }
                }
            }
        }
    } catch (Exception ioe) {
        getLogger().log(Level.SEVERE, "Failed to read range '" + m_SheetRange + "':", ioe);
        result = null;
        m_LastError = "Failed to read range '" + m_SheetRange + "' from stream!\n"
                + Utils.throwableToString(ioe);
    }

    return result;
}

From source file:adams.gui.tools.previewbrowser.ExcelSpreadSheetHandler.java

License:Open Source License

/**
 * Determines the number of sheets in the spreadsheet file.
 *
 * @param file   the spreadsheet file to check
 * @return      the number of sheets//from  www .j  a  va  2s  .  co  m
 */
protected int getSheetCount(File file) {
    int result;
    Workbook workbook;
    FileInputStream fis;
    BufferedInputStream input;

    input = null;
    fis = null;
    try {
        fis = new FileInputStream(file.getAbsoluteFile());
        input = new BufferedInputStream(fis);
        workbook = WorkbookFactory.create(input);
        result = workbook.getNumberOfSheets();
    } catch (Exception e) {
        result = 0;
        getLogger().log(Level.SEVERE, "Failed to determine sheet count for '" + file + "':", e);
    } finally {
        FileUtils.closeQuietly(input);
        FileUtils.closeQuietly(fis);
    }

    return result;
}

From source file:android_connector.ConfigWindowController.java

/**
 * Liest eine Excel-Datei ein und entnimmt dieser die Werte fr Startnummer,
 * Name und Kategorie. Fgt die Werte anschlieend der Tabelle hinzu.
 *
 * @param event Klick auf Button, der die Methode aufruft
 *//*from   w  w  w. ja v a2  s  .c  o m*/
@FXML
private void readExcel(ActionEvent event) {
    //Rcksetzen der Tabelle
    tabelle.setItems(FXCollections.observableArrayList());
    personData = tabelle.getItems();
    //FileChooser einsetzen, um Starterplan einzulesen
    FileChooser fc = new FileChooser();
    //standardmig im Home-Verzeichnis starten
    fc.setInitialDirectory(new File(System.getProperty("user.home")));
    //Alle-Dateien-Filter entfernen
    fc.setSelectedExtensionFilter(null);
    //FileFilter fr Exceldateien hinzufgen
    //nur "alte" Excel-Dateien knnen gelesen werden!
    fc.getExtensionFilters()
            .addAll(new FileChooser.ExtensionFilter("Microsoft Excel 1997-2003 Dokument (.xls)", "*.xls"));
    //Dateien einlesen
    File returnVal = fc.showOpenDialog(primaryStage);
    //prfen, ob Datei zurckgegeben --> eine gewhlt; muss aber nicht existieren
    if (returnVal != null) {
        //ExcelReader anlegen, der Datei dann in den Speicher vergewaltigt.
        ExcelReader reader = null;
        /**
         * Speichert, ob es beim Laden Probleme gab. True, wenn alles gut
         * ist, sonst false.
         */
        boolean geladen = true;
        //Versuch, Datei zu laden
        try {
            reader = new ExcelReader(returnVal.getAbsolutePath());
        } catch (IOException ex) {
            //Exception fangen, die durch Ladefehler entsteht, und diese mit ExceptionDialog anzeigen
            new MySQLConnection(null).showExceptionDialog(ex, "Lesefehler",
                    "Datei konnte nicht gelesen werden.",
                    "Die Datei " + returnVal.getAbsolutePath()
                            + " konnte nicht gelesen werden. Bitte geben Sie bei einer Beschwerde an den Entwickler folgende Fehlermeldung an: ",
                    false);
            //Fehler aufgetreten
            geladen = false;
        }
        //prfen, ob Fehler
        if (geladen) {
            //Datei geladen --> ExcelReader nicht null, kann referiert werden
            Workbook wb = reader.getWorkBook();
            //Datei hat nur 1 Tabelle --> direkt die nehmen
            if (wb.getNumberOfSheets() == 1) {
                reader.setSheet(0);
            } else {
                //mehrere Tabellen --> User muss whlen, welche er will
                List<String> items = new ArrayList<>();
                //Nahmen aller Tabellen in Liste speichern
                for (int i = 0; i < wb.getNumberOfSheets(); i++) {
                    items.add(wb.getSheetName(i));
                }
                //ChoiceDialog anzeigen, der die Auswahl ermglicht
                ChoiceDialog<String> dialog = new ChoiceDialog<>(items.get(0), items);
                dialog.setTitle("Tabelle auswhlen");
                dialog.setHeaderText("Bitte Tabelle auswhlen!");
                dialog.setContentText("In der bergebenen Datei wurden " + wb.getNumberOfSheets()
                        + " Tabellen gefunden. Bitte whlen Sie die gewnschte Tabelle aus!");

                Optional<String> result = dialog.showAndWait();
                // The Java 8 way to get the response value (with lambda expression).
                /**
                 * Finale Kopie des readers, der von Lambda adressiert
                 * werden kann.
                 */
                final ExcelReader temp = reader;
                result.ifPresent(letter -> {
                    //Tabelle laden, die gewhlt wurde.
                    temp.setSheet(wb.getSheet(letter));
                });
                //nderungen bernehmen
                reader = temp;
            }
            //erste drei Spalten durchgehen, erste Zeile berspringen (Beschriftung), danach erste Spalte als Startnummer, zweite als Nahme, dritte als Kategorie interpretieren
            for (int i = 1; i < reader.getSheet().getLastRowNum() + 1; i++) {
                //Person-Objekt bilden, das Werte der Person in den Zeilen enthlt
                //Startnummern werden als Doubles gelesen, Umwandlung in int
                Person e = new Person((new Double(reader.getCellValueAt(i, 0))).intValue() + "",
                        reader.getCellValueAt(i, 1), reader.getCellValueAt(i, 2));
                //Starter den Personen hinzufgen ...
                personData.add(e);
                //... und ihre Zahl erhhen
                starter++;
            }
            //genderte Starter in Tabelle bernehmen
            tabelle.setItems(personData);
        }
    }
}

From source file:au.com.onegeek.lambda.parser.Excel2SeleniumParser.java

License:Apache License

private void parse(InputStream stream)
        throws CannotCompileException, NotFoundException, CannotCreateTestClassException,
        InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {

    logger.debug("Parsing...");

    if (this.dataMap != null && this.tests != null) {
        return;//from  ww w  . ja  v a 2s . co  m
    }

    this.dataMap = new ArrayList<Map<String, Object>>();
    this.tests = new ArrayList<Class<Test>>();

    Workbook workbook = null;
    try {
        workbook = new XSSFWorkbook(stream);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    logger.debug("workbook" + workbook.toString());

    for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
        Sheet sheet = workbook.getSheetAt(i);
        if (sheet.getSheetName().startsWith("data")) {
            // parse key\value pairs
            HashMap<String, Object> map = new HashMap<String, Object>();
            dataMap.add(map);
            boolean done = false;

            Row row = sheet.getRow(sheet.getFirstRowNum());

            while (!done && row != null && row.getPhysicalNumberOfCells() > 0) {
                // TODO: parse numerics correctly (i.e. don't add decimal points if not needed)
                String key = (String) XslxUtil.objectFrom(workbook, row.getCell(0));
                String value = null;
                try {
                    value = (String) XslxUtil.objectFrom(workbook, row.getCell(1));
                    logger.debug("Adding variable to map: " + key + ":" + value);
                    map.put(key, value);

                    row = sheet.getRow(row.getRowNum() + 1);

                    if (row == null || (row.getRowNum() == sheet.getLastRowNum() + 1)) {
                        done = true;
                    }
                } catch (NullPointerException e) {
                    //throw new CannotCreateVariableException("No value found for variable '" + key + "' in dataset: " + sheet.getSheetName());
                    done = true;
                }
            }
        }
    }

    JavassistTestBuilderImpl builder = JavassistTestBuilderImpl.getInstance();

    // Parse Test sheets into Test objects
    for (int s = 0; s < workbook.getNumberOfSheets(); s++) {
        Sheet sheet = workbook.getSheetAt(s);
        int i = 0;

        // Ignore data sheets
        if (sheet.getSheetName().startsWith("suite")) {

            int maxRows = sheet.getPhysicalNumberOfRows();
            int currentRow = sheet.getFirstRowNum();
            logger.debug("Nr rows in sheet: " + maxRows);

            // Create Test Class
            String testCaseName = "Test" + Excel2SeleniumParser.toCamelCase(sheet.getSheetName());
            logger.debug("Creating Test class with name: " + testCaseName);
            builder.makeTestClass(testCaseName, this.dataMap);
            boolean testCaseInProgress = false;
            boolean dataProviderAdded = false;

            // Get First row, containing the test name and the data to be injected
            while (i < maxRows) {
                logger.debug("i: " + i);
                logger.debug("currentRow: " + currentRow);
                Row row = sheet.getRow(currentRow);
                TestCommand command = null;

                // Check for empty row
                if (row != null && row.getPhysicalNumberOfCells() != 0) {
                    i++;

                    // Get Cells
                    Iterator<Cell> iterator = row.cellIterator();
                    while (iterator.hasNext()) {
                        Cell cell = iterator.next();
                        String cellValue = (cell == null || cell.toString() == "") ? ""
                                : XslxUtil.objectFrom(workbook, cell).toString();
                        logger.debug("Cell: " + cellValue);

                        if (cellValue.startsWith("test")) {
                            logger.debug("Test case found: " + cellValue + ". Creating Test Case");

                            // Create new Test CASE
                            try {
                                builder.addTest(cellValue);
                                testCaseInProgress = true;
                                dataProviderAdded = false;
                            } catch (CannotModifyTestMethodException e) {
                                e.printStackTrace();
                                throw new CannotCreateTestClassException(
                                        "Could not create Test Class as there was a variable not found in test assertion. Embedded exception: "
                                                + e.getMessage());
                            } catch (VariableNotFoundException e) {
                                e.printStackTrace();
                                throw new CannotCreateTestClassException(
                                        "Could not create Test Class as there was a variable not found in test assertion. Embedded exception: "
                                                + e.getMessage());
                            }
                            break;
                        } else {
                            if (command == null & !cellValue.equals("")) {
                                logger.debug("Command found: " + cellValue + ". Creating new TestCommand");
                                command = new TestCommand(cellValue);
                            } else if (!cellValue.equals("")) {
                                logger.debug("Command argument found: " + cellValue);
                                command.addParameter(cellValue);
                            }
                        }
                    }
                } else {
                    // Blank row could mean a test case has just been completed
                    // Complete last test case by adding a data provider
                    if (testCaseInProgress && !dataProviderAdded) {
                        try {
                            logger.debug("In Progress Test Case now being closed off and added to class...");
                            builder.addDataProvider();
                            dataProviderAdded = true;
                            logger.debug("In Progress Test Case now closed off!");
                        } catch (CannotCreateDataProviderException e) {
                            throw new CannotCreateTestClassException(
                                    "Could not create Test case as a DataProvider for the method could not be created. Embedded exception: "
                                            + e.getMessage());
                        }
                    }
                }
                try {
                    if (command != null) {
                        logger.debug("Adding command to method");
                        builder.appendTestToLastMethod(command);
                    }
                } catch (CannotModifyTestMethodException e) {
                    throw new CannotCreateTestClassException("Unable to add Test Case '" + command.toString()
                            + "' to Test Class. Embedded exception: " + e.getMessage());
                } catch (VariableNotFoundException e) {
                    throw new CannotCreateTestClassException("Unable to add Test Case '" + command.toString()
                            + "' to Test Class as a variable was not found. Embedded exception: "
                            + e.getMessage());
                }
                currentRow++;
            }
            // Blank row could mean a test case has just been completed
            // Complete last test case by adding a data provider
            logger.debug(
                    "End of rows...Checking if In Progress Test Case now being closed off and added to class...");
            if (testCaseInProgress && !dataProviderAdded) {
                logger.debug(" In Progress Test Case now being closed off and added to class...");
                try {
                    builder.addDataProvider();
                    dataProviderAdded = true;
                    logger.debug("In Progress Test Case now closed off!");
                } catch (CannotCreateDataProviderException e) {
                    throw new CannotCreateTestClassException(
                            "Could not create Test case as a DataProvider for the method could not be created. Embedded exception: "
                                    + e.getMessage());
                }
            }

            if (testCaseInProgress) {
                logger.debug("Generating class file");
                try {
                    this.tests.add(builder.getCreatedClass());
                } catch (CannotModifyTestMethodException e) {
                    e.printStackTrace();
                    throw new CannotCreateTestClassException(
                            "Could not create Test case as a DataProvider for the method could not be created. Embedded exception: "
                                    + e.getMessage());
                }
                testCaseInProgress = false;
            }
        }
    }

    try {
        stream.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    logger.info("Looking at our classes...");

    // Look at the Test Objects
    for (Class<Test> clazz : tests) {
        logger.info("Class: " + clazz.getName());
        for (Method m : clazz.getMethods()) {
            logger.info("Method: " + m);
            if (m.getName().equalsIgnoreCase("testRetailDataProvider")) {
                logger.info("invoking data provider");
                Test test = clazz.newInstance();
                Object[][] data = (Object[][]) m.invoke(test);
                for (Object[] obs : data) {
                    for (Object o : obs) {
                        logger.info("data value: " + o);
                    }
                }
            }
        }
    }
}

From source file:bad.robot.excel.matchers.SheetNumberMatcher.java

License:Apache License

@Override
protected boolean matchesSafely(Workbook actual, Description mismatch) {
    if (expected.getNumberOfSheets() != actual.getNumberOfSheets()) {
        mismatch.appendText("got ").appendValue(actual.getNumberOfSheets()).appendText(" sheet(s) expected ")
                .appendValue(expected.getNumberOfSheets());
        return false;
    }/*  w  w w  .  j a v  a 2s .c  o  m*/
    return true;
}

From source file:bandaru_excelreadwrite.ReadfromExcel.java

public List getSongsListFromExcel() {
    List songList = new ArrayList();
    FileInputStream fis = null;//from   w  w  w  . j a  va 2  s  . c o m

    try {
        fis = new FileInputStream(FILE_PATH);

        /*
          Use XSSF for xlsx format, for xls use HSSF
        */
        Workbook workbook = new XSSFWorkbook(fis);

        int numberOfSheets = workbook.getNumberOfSheets();

        /*
        looping over each workbook sheet
        */
        for (int i = 0; i < numberOfSheets; i++) {
            Sheet sheet = workbook.getSheetAt(i);
            Iterator rowIterator = sheet.iterator();

            /*
                iterating over each row
                */
            while (rowIterator.hasNext()) {

                Song song = new Song();
                Row row = (Row) rowIterator.next();

                Iterator cellIterator = row.cellIterator();
                while (cellIterator.hasNext()) {

                    Cell cell = (Cell) cellIterator.next();

                    /*
                    checking if the cell is having a String value .
                    */
                    if (Cell.CELL_TYPE_STRING == cell.getCellType()) {

                        /*
                        Cell with index 1 contains Album name 
                        */
                        if (cell.getColumnIndex() == 1) {
                            song.setAlbumname(cell.getStringCellValue());
                        }

                        /*
                        Cell with index 2 contains Genre
                        */
                        if (cell.getColumnIndex() == 2) {
                            song.setGenre(cell.getStringCellValue());
                        }

                        /*
                        Cell with index 3 contains Artist name
                        */
                        if (cell.getColumnIndex() == 3) {
                            song.setArtist(cell.getStringCellValue());
                        }

                    }

                    /*
                     checking if the cell is having a numeric value
                    */
                    else if (Cell.CELL_TYPE_NUMERIC == cell.getCellType()) {

                        /*
                        Cell with index 0 contains Sno
                        */
                        if (cell.getColumnIndex() == 0) {
                            song.setSno((int) cell.getNumericCellValue());
                        }

                        /*
                        Cell with index 5 contains Critic score.
                        */
                        else if (cell.getColumnIndex() == 5) {
                            song.setCriticscore((int) cell.getNumericCellValue());
                        }

                        /*
                        Cell with index 4 contains Release date
                        */
                        else if (cell.getColumnIndex() == 4) {
                            Date dateValue = null;

                            if (DateUtil.isCellDateFormatted(cell)) {
                                dateValue = cell.getDateCellValue();
                            }
                            song.setReleasedate(dateValue);
                        }

                    }

                }

                /*
                end iterating a row, add all the elements of a row in list
                */
                songList.add(song);
            }
        }

        fis.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return songList;
}

From source file:biz.webgate.domino.poi.demodb.poweraction.WorkbookUpload.java

License:Apache License

public List<String> getSheetNames() {
    List<String> lstRC = new ArrayList<String>();
    if (m_File != null) {
        if (last_File != m_File) {
            last_File = m_File;
            IUploadedFile FTemp = m_File.getUploadedFile();
            String inputFile = FTemp.getServerFile().getPath();
            ImportAction ioAction = new ImportAction();
            HashMap<String, String> hsCurrent = new HashMap<String, String>();
            hsCurrent.put("FILE", inputFile);
            Workbook wb = ioAction.run(null, hsCurrent);
            if (ioAction.hasError()) {
                Exception exLst = ioAction.getLastException();
                StringWriter swCurrent = new StringWriter();
                PrintWriter pwCurrent = new PrintWriter(swCurrent);
                exLst.printStackTrace(pwCurrent);
                lstRC.add("ERROR !!!!");
                String[] arrErr = swCurrent.toString().split("\n");
                lstRC.addAll(Arrays.asList(arrErr));
            } else {
                for (int nCount = 0; nCount < wb.getNumberOfSheets(); nCount++) {
                    lstRC.add(wb.getSheetName(nCount));
                }/*from  ww  w .j a v  a  2  s  . c  o m*/
            }
            m_SheetNames = lstRC;
        }
    }
    return m_SheetNames;
}

From source file:blanco.commons.calc.parser.AbstractBlancoCalcParser.java

License:Open Source License

/**
 * ???/*from  w  w  w.  j  a  va2 s  .  co m*/
 * 
 * @param workbook
 *            
 * @throws SAXException
 *             SAX????
 */
private void parseWorkbook(final Workbook workbook) throws SAXException {
    getContentHandler().startDocument();
    getContentHandler().startElement("", (String) getProperty(URI_PROPERTY_NAME_WORKBOOK),
            (String) getProperty(URI_PROPERTY_NAME_WORKBOOK), new AttributesImpl());

    for (int indexSheet = 0; indexSheet < workbook.getNumberOfSheets(); indexSheet++) {
        Sheet sheet = workbook.getSheetAt(indexSheet);
        parseSheet(sheet);
    }
    getContentHandler().endElement("", (String) getProperty(URI_PROPERTY_NAME_WORKBOOK),
            (String) getProperty(URI_PROPERTY_NAME_WORKBOOK));
    getContentHandler().endDocument();
}

From source file:br.com.gartech.nfse.integrador.util.ExcelHelper.java

private String workbook2xml(org.apache.poi.ss.usermodel.Workbook workbook) {
    String result = null;//from ww  w .  j av  a  2s  .com
    StringBuffer sb = null;
    Sheet sheet = null;

    if (workbook != null && workbook.getSheetAt(0) != null) {
        String newLine = System.getProperty("line.separator");

        sb = new StringBuffer();
        sb.append("<?xml version=\"1.0\" ?>");
        sb.append(newLine);
        sb.append("<!DOCTYPE workbook SYSTEM \"workbook.dtd\">");
        sb.append(newLine);
        sb.append(newLine);
        sb.append("<workbook>");
        sb.append(newLine);

        for (int i = 0; i < workbook.getNumberOfSheets(); ++i) {

            sheet = workbook.getSheetAt(i);

            if (sheet != null && sheet.rowIterator().hasNext()) {

                sb.append("\t");
                sb.append("<sheet>");
                sb.append(newLine);
                sb.append("\t\t");
                sb.append("<name><![CDATA[" + sheet.getSheetName() + "]]></name>");
                sb.append(newLine);

                int j = 0;

                for (Iterator<Row> iterator = sheet.rowIterator(); iterator.hasNext();) {
                    Row row = (Row) iterator.next();

                    int k = 0;

                    if (row.getCell(0) != null && row.getCell(0).getStringCellValue() != null
                            && row.getCell(0).getStringCellValue().trim().length() > 0) {

                        sb.append("\t\t");
                        sb.append("<row number=\"" + j + "\">");
                        sb.append(newLine);

                        for (Cell cell : row) {
                            sb.append("\t\t\t");
                            sb.append("<col number=\"" + k + "\">");
                            sb.append("<![CDATA[" + cellToString(cell) + "]]>");
                            sb.append("</col>");
                            sb.append(newLine);
                            k++;
                        }

                        sb.append("\t\t");
                        sb.append("</row>");
                        sb.append(newLine);
                    }

                    j++;

                }

                sb.append("\t");
                sb.append("</sheet>");
                sb.append(newLine);

            }
        }

        sb.append("</workbook>");
        sb.append(newLine);

        result = sb.toString();
    }

    return result;
}