Example usage for org.apache.poi.ss.usermodel WorkbookFactory create

List of usage examples for org.apache.poi.ss.usermodel WorkbookFactory create

Introduction

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

Prototype

public static Workbook create(File file) throws IOException, EncryptedDocumentException 

Source Link

Document

Creates the appropriate HSSFWorkbook / XSSFWorkbook from the given File, which must exist and be readable.

Usage

From source file:midas.sheeco.Sheeco.java

License:Apache License

public <T> List<T> fromSpreadsheet(final InputStream stream, final Class<T> payloadClass)
        throws SpreadsheetUnmarshallingException, SpreasheetUnmarshallingUnrecoverableException {
    try {// w w  w  .java  2s .  c  o m
        final Workbook wb = WorkbookFactory.create(stream);
        final Payload<T> payload = new Payload<>(payloadClass);

        final Sheet sheet = getSheet(payload.getName(), wb);

        final FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();

        final PayloadContext<T> ctx = new PayloadContext<>(sheet, evaluator, payload);
        final List<T> payloads = readPayloads(ctx);

        if (ctx.getViolations().isEmpty()) {
            return payloads;
        } else {
            throw new SpreadsheetUnmarshallingException(payloads, ctx.getViolations());
        }

    } catch (final FileNotFoundException e) {
        throw new SpreasheetUnmarshallingUnrecoverableException(
                String.format("sheeco.serializer.file.cannot.open"));
    } catch (final IOException | InvalidFormatException e) {
        throw new SpreasheetUnmarshallingUnrecoverableException(
                String.format("sheeco.serializer.file.wrong.format"));
    }
}

From source file:misuExcel.excelRead.java

License:Open Source License

public void createExcel() {
    InputStream inps = null;//  w  w  w. j av  a2  s. c o m
    try {
        inps = new FileInputStream(getFile());
    } catch (FileNotFoundException e) {
        Log.warm(e.getCause().getMessage());
    }

    if (inps != null) {
        try {
            wb = WorkbookFactory.create(inps);
            switch (type) {
            case 1:
                //               windows.readyEx01=true;
                //               System.err.println("first excel is already");
                break;
            case 2:
                //               System.err.println("second already");
                //               windows.readyEx02=true;
                break;

            default:
                break;
            }
        } catch (InvalidFormatException e) {
            Log.warm(e.getCause().getMessage());
        } catch (IOException e) {
            Log.warm(e.getCause().getMessage());
        }
    }
}

From source file:Model.ExcelModel.java

public String ImportFile(File fileImported, JTable dataTable) {
    String importResult = "System couldn't import the file";

    DefaultTableModel loadModel = new DefaultTableModel();
    dataTable.setModel(loadModel);//w  w w  . j av  a  2 s.  com
    dataTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

    try {
        innerWorkbook = WorkbookFactory.create(new FileInputStream(fileImported));
        Sheet sheetTemporal = innerWorkbook.getSheetAt(0);
        Iterator rowIterator = sheetTemporal.rowIterator();

        int rowIndex = -1;
        while (rowIterator.hasNext()) {
            rowIndex++;

            Row temporalRow = (Row) rowIterator.next();
            Iterator columnIterator = temporalRow.cellIterator();

            Object[] columnList = new Object[12];

            int columnIndex = -1;
            while (columnIterator.hasNext()) {
                columnIndex++;
                Cell temporalCell = (Cell) columnIterator.next();
                if (rowIndex == 0)
                    loadModel.addColumn(temporalCell.getStringCellValue());
                else {
                    if (temporalCell != null) {
                        switch (temporalCell.getCellType()) {
                        case Cell.CELL_TYPE_NUMERIC:
                            columnList[columnIndex] = (int) Math.round(temporalCell.getNumericCellValue());
                            break;
                        case Cell.CELL_TYPE_STRING:
                            columnList[columnIndex] = temporalCell.getStringCellValue();
                            break;
                        default:
                            columnList[columnIndex] = temporalCell.getDateCellValue();
                            break;
                        }//End Switch/Case get.CellType
                    } //End temporalCell!=null condition
                } //End Else rowIndex==0
            } //End columnIterator
            if (rowIndex != 0)
                loadModel.addRow(columnList);
        } //End rowIterator

        importResult = "Successful Import";

    } catch (Exception e) {
    }
    return importResult;

}

From source file:Modelo.ModeloExcel.java

public String Importar(File archivo, JTable tablaD) {
    String respuesta = "No se pudo realizar la importacin.";
    DefaultTableModel modeloT = new DefaultTableModel();
    tablaD.setModel(modeloT);//from ww  w .j  ava  2 s . c o m
    try {
        wb = WorkbookFactory.create(new FileInputStream(archivo));
        Sheet hoja = wb.getSheetAt(0);
        Iterator filaIterator = hoja.rowIterator();
        int indiceFila = -1;
        while (filaIterator.hasNext()) {
            indiceFila++;
            Row fila = (Row) filaIterator.next();
            Iterator columnaIterator = fila.cellIterator();
            Object[] listaColumna = new Object[5];
            int indiceColumna = -1;
            while (columnaIterator.hasNext()) {
                indiceColumna++;
                Cell celda = (Cell) columnaIterator.next();
                if (indiceFila == 0) {
                    modeloT.addColumn(celda.getStringCellValue());
                } else {
                    if (celda != null) {
                        switch (celda.getCellType()) {
                        case Cell.CELL_TYPE_NUMERIC:
                            listaColumna[indiceColumna] = (int) Math.round(celda.getNumericCellValue());
                            break;
                        case Cell.CELL_TYPE_STRING:
                            listaColumna[indiceColumna] = celda.getStringCellValue();
                            break;
                        case Cell.CELL_TYPE_BOOLEAN:
                            listaColumna[indiceColumna] = celda.getBooleanCellValue();
                            break;
                        default:
                            listaColumna[indiceColumna] = celda.getDateCellValue();
                            break;
                        }
                    }
                }
            }
            if (indiceFila != 0)
                modeloT.addRow(listaColumna);
        }
        respuesta = "Importacin exitosa";
    } catch (Exception e) {
    }
    return respuesta;
}

From source file:net.bafeimao.umbrella.support.data.entity.ExcelEntityParser.java

License:Apache License

/**
 * Excel?Sheet???,?clazz//from  w  ww .j  a  v  a 2 s .com
 * <p/>
 * TODO {@link PrintExecutionTime}?AOP?
 */
@Override
@PrintExecutionTime
public <E extends DataEntity> LinkedList<E> parse(Class<E> entityClass) throws EntityParseException {
    LinkedList<E> entities = null;
    InputStream inputStream = null;

    try {
        ExcelMapping mapping = entityClass.getAnnotation(ExcelMapping.class);
        String fileName = "e:\\" + mapping.file();
        String sheetName = mapping.sheet();

        inputStream = new FileInputStream(fileName); // FileInputStream?Excel?
        Workbook wb = WorkbookFactory.create(inputStream); // Workbook,?excelsheet

        if (wb != null && wb.getNumberOfSheets() > 0) {
            Sheet sheet = wb.getSheet(sheetName);

            // ???
            if (sheet.getRow(0) != null) {
                entities = parse0(entityClass, sheet);
            }
        }
    } catch (Exception e) {
        LOGGER.error("{}", e);
    } finally {
        try {
            if (inputStream != null)
                inputStream.close();
        } catch (IOException e) {
            LOGGER.error("{}", e);
        }
    }

    return entities;
}

From source file:net.morphbank.loadexcel.ReadExternalLinks.java

License:Open Source License

public ReadExternalLinks(String filename, GetConnection conn) {
    connect = conn;/*  w ww.  j  a  v a 2 s.  co  m*/
    String fname = filename;

    result = null;
    statement = null;
    metadata = null;

    try {
        InputStream inp = new FileInputStream(fname);
        Workbook workbook = WorkbookFactory.create(inp);

        // extract the sheets from a formed workbook
        Links = workbook.getSheetAt(0);

    } catch (Exception ioexception) {
        ioexception.printStackTrace();
    }
}

From source file:net.morphbank.loadexcel.SheetReader.java

License:Open Source License

public SheetReader(String filename, GetConnection conn) {
    connect = conn;//from   ww  w  . ja  v  a 2  s. c o m
    fname = filename;

    result = null;
    statement = null;
    metadata = null;

    try {

        InputStream inp = new FileInputStream(fname);
        Workbook workbook = WorkbookFactory.create(inp);

        // extract the sheets from a formed workbook
        imageCollectionSheet = workbook.getSheetAt(0);
        imageSheet = workbook.getSheetAt(1);
        viewSheet = workbook.getSheetAt(2);
        taxonSheet = workbook.getSheetAt(4);
        specimenSheet = workbook.getSheetAt(3);
        localitySheet = workbook.getSheetAt(5);
        extLinkSheet = workbook.getSheetAt(6);
        supportDataSheet = workbook.getSheetAt(7);
        protectedDataSheet = workbook.getSheetAt(9);
        readHeaders();
        setReleaseDate();

    } catch (Exception ioexception) {
        ioexception.printStackTrace();
    }
}

From source file:net.morphbank.mbsvc3.fsuherb.XlsFieldMapper.java

License:Open Source License

public XlsFieldMapper(String fileName) {
    try {/*www . j av a 2 s. c o  m*/
        this.fileName = fileName;
        InputStream inp = new FileInputStream(fileName);
        Workbook workbook = WorkbookFactory.create(inp);
        views = workbook.getSheetAt(0);
        readHeaders();
        lastLine = views.getLastRowNum() - 1;
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:net.morphbank.mbsvc3.mapsheet.XlsFieldMapper.java

License:Open Source License

public XlsFieldMapper(String fileName) {
    try {/* ww w  .  j  ava 2s.com*/

        this.fileName = fileName;
        InputStream inp = new FileInputStream(fileName);
        Workbook workbook = WorkbookFactory.create(inp);
        views = workbook.getSheetAt(0);
        credentialSheet = workbook.getSheetAt(2);
        links = workbook.getSheetAt(1);
        readHeaders();
        lastLine = views.getLastRowNum() - 1;

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:net.pcal.sqlsheet.XlsDriver.java

License:Apache License

public Connection connect(String jdbcUrl, Properties info) throws SQLException {
    if (jdbcUrl == null)
        throw new IllegalArgumentException("Null url");
    if (!acceptsURL(jdbcUrl))
        return null; // why is this necessary?
    if (!jdbcUrl.toLowerCase().startsWith(URL_SCHEME)) {
        throw new IllegalArgumentException("URL is not " + URL_SCHEME + " (" + jdbcUrl + ")");
    }//from w w w . j av  a 2 s .  c  o  m
    // strip any properties from end of URL and set them as additional properties
    String urlProperties;
    int questionIndex = jdbcUrl.indexOf('?');
    if (questionIndex >= 0) {
        info = new Properties(info);
        urlProperties = jdbcUrl.substring(questionIndex);
        String[] split = urlProperties.substring(1).split("&");
        for (String each : split) {
            String[] property = each.split("=");
            try {
                if (property.length == 2) {
                    String key = URLDecoder.decode(property[0], "UTF-8");
                    String value = URLDecoder.decode(property[1], "UTF-8");
                    info.setProperty(key, value);
                } else if (property.length == 1) {
                    String key = URLDecoder.decode(property[0], "UTF-8");
                    info.setProperty(key, Boolean.TRUE.toString());
                } else {
                    throw new SQLException("Invalid property: " + each);
                }
            } catch (UnsupportedEncodingException e) {
                // we know UTF-8 is available
            }
        }
        jdbcUrl = jdbcUrl.substring(0, questionIndex);
    }
    try {
        URL workbookUrl = new URL(jdbcUrl.substring(URL_SCHEME.length()));
        //If streaming requested for read
        if (has(info, READ_STREAMING)) {
            return new XlsStreamConnection(workbookUrl);
        } else if (workbookUrl.getProtocol().equalsIgnoreCase("file")) {
            //If streaming requested for write
            if (has(info, WRITE_STREAMING)) {
                return new XlsConnection(getOrCreateXlsxStream(workbookUrl), new File(workbookUrl.getPath()),
                        info);
            }
            return new XlsConnection(getOrCreateWorkbook(workbookUrl), new File(workbookUrl.getPath()), info);
        } else {
            //If plain url provided
            return new XlsConnection(WorkbookFactory.create(workbookUrl.openStream()), info);
        }
    } catch (Exception e) {
        SQLException sqe = new SQLException(e.getMessage());
        sqe.initCause(e);
        throw sqe;
    }
}