Example usage for org.apache.poi.poifs.filesystem POIFSFileSystem POIFSFileSystem

List of usage examples for org.apache.poi.poifs.filesystem POIFSFileSystem POIFSFileSystem

Introduction

In this page you can find the example usage for org.apache.poi.poifs.filesystem POIFSFileSystem POIFSFileSystem.

Prototype


public POIFSFileSystem(InputStream stream) throws IOException 

Source Link

Document

Create a POIFSFileSystem from an InputStream.

Usage

From source file:blueprint.sdk.experimental.util.XlsReader.java

License:Open Source License

/**
 * Opens Migration Plan (*.xls) file//from  w w w  . ja v a2s.c o m
 *
 * @throws IOException Failed to open or read *.xls file
 */
public void open() throws IOException {
    InputStream input = new FileInputStream(filePath);
    wbook = new HSSFWorkbook(new POIFSFileSystem(input));
    evaluator = new HSSFFormulaEvaluator(wbook);
}

From source file:br.com.tiagods.model.Arquivo.java

public Workbook validarWorkbook(Workbook workbook, File file, String ext, InputStream inputStream) {
    switch (ext) {
    case "xls":
        try {//from   ww  w  .jav  a  2  s.  co m
            if (file.getName().equals("Cadastro.xls")) {//formula para abrir arquivo com senha
                Biff8EncryptionKey.setCurrentUserPassword("PLKCONTRATOS");
                NPOIFSFileSystem fs = new NPOIFSFileSystem(file, true);
                return workbook = new HSSFWorkbook(fs.getRoot(), true);
            } else {
                POIFSFileSystem fileSystem = new POIFSFileSystem(inputStream);
                return workbook = new HSSFWorkbook(fileSystem);
            }
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, e);
            return null;
        }
    case "xlsx":
        try {
            return workbook = new XSSFWorkbook(inputStream);
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, e);
            return null;
        }
    default:
        JOptionPane.showMessageDialog(null, "Formato de arquivo no permitido!");
        return null;
    }
}

From source file:br.eti.rogerioaguilar.minhasclasses.util.excel.leitor.LeitorExcel.java

License:Open Source License

/**
 * Realiza o processamento de leitura seguindo o fluxo:
 * /*from   w  w w.  ja  v a  2 s  .c om*/
 * 1 - O leitor abre a planilha                                                            <br>
 * 2 - o leitor comea a ler as linhas e colunas da planilha                                    <br>
 * 3 - Para cada linha encontrada:                                                         <br>
 *          3.1 - Caso a linha esteja na lista de linhas que devem ser processadas passada ao construtor:         <br>
 *                  3.1.1 - O leitor monta uma lista de vos contendos os dados das colunas para a linha atual que      <br>
 *                        estejam dentro do padro de leitura passado ao construtor                           <br>
 *                 3.1.2 - O leitor chama o mtodo LinhaListener.lendoLinha passando o mapa com os dados da linha      <br>
 *                       e aguarda o final do processamento.                                          <br>
 *                       3.1.2.1 - Caso o mtodo do listener retorne true, o leitor continua o processamento da     <br>
 *                               da planilha. Caso contrrio, o processamento da planilha  interrompido         <br>
 *                                 Se o processamento da planilha continuar (de acordo com o parmetro de retorno   <br>
 *                               do listener para a linha descrito anteriormente), o leitor chama o listener para <br>
 *                               a coluna para cada coluna da linha atual. O comportamento deste listener  o mesmo <br>
 *                               do listener para a linha, ou seja, se o listener retornar false o processamento da <br>
 *                               planilha  interrompido.   
 * 
 * @throws ParseException
 * @throws PlanilhaNaoEncontradaException caso o ndice da planilha no seja encontrado no arquivo
 * @throws FileNotFoundException caso o arquivo passado como parmetro no exista
 * @throws ListenerException caso ocorra algum erro na chamada de algum dos listeners
 * @throws IOException caso ocorra algum problema de io
 * */
public void processarLeituraPlanilha() throws ParseException, PlanilhaNaoEncontradaException,
        FileNotFoundException, IOException, ListenerException {

    try {
        log.debug("Inicializando o processamento da leitura do arquivo...");
        log.debug("Dados para o processamento --> " + this);
        POIFSFileSystem fs = null;
        if (this.streamArquivo != null) {
            fs = new POIFSFileSystem(streamArquivo);
        } else if (this.caminhoArquivoExcel != null) {
            fs = new POIFSFileSystem(new FileInputStream(this.caminhoArquivoExcel));
        } else {
            throw new IllegalArgumentException(
                    "No foi definido um stream para o arquivo nem um caminho para o arquivo!");
        }
        log.debug("Processando a string de entrada --> " + this.strPadraoLeitura);
        Map mapaLinhasAProcessar = LeitorExcelReader
                .getMapaEntradas(new ByteArrayInputStream(this.strPadraoLeitura.getBytes()));
        log.debug("A string de entrada --> " + this.strPadraoLeitura + " foi processada com sucesso.");
        log.debug("Mapa retornado --> " + mapaLinhasAProcessar);

        HSSFWorkbook wb = new HSSFWorkbook(fs);
        HSSFSheet planilha = wb.getSheetAt(this.indicePlanilha - 1);
        if (planilha == null) {
            log.error("Planilha no encontrada no ndice -->" + this.indicePlanilha);
            throw new PlanilhaNaoEncontradaException(
                    "Planilha no encontrada no ndice -->" + this.indicePlanilha);
        } else {
            log.debug("A string de entrada --> " + this.strPadraoLeitura + " foi processada com sucesso.");
            boolean processarTodasAsLinhas = (mapaLinhasAProcessar.get("*") != null);
            boolean processarTodasAsColunas = false;
            boolean continuarProcessamentoLinha = true;
            Map propriedadesListenerLinha = new HashMap();
            Map propriedadesListenerColuna = new HashMap();
            List listaColunas = null;
            List listaVosColunas = new LinkedList();
            if (processarTodasAsLinhas) {
                log.debug("Processando todas as linhas...");
            }
            Iterator itLinhas = planilha.rowIterator();
            while (itLinhas.hasNext() && continuarProcessamentoLinha) {
                HSSFRow linha = (HSSFRow) itLinhas.next();
                propriedadesListenerLinha.clear();
                listaVosColunas.clear();
                propriedadesListenerLinha.put(LinhaListener.CHAVE_LINHA_OBJETO_ORIGINAL_POI, linha);
                int intLinhaAtual = linha.getRowNum() + 1;

                log.debug("Processando linha --> " + intLinhaAtual);
                if (!processarTodasAsLinhas) {
                    listaColunas = getListaColunasLinha("" + intLinhaAtual, mapaLinhasAProcessar);
                } else {
                    listaColunas = getListaColunasLinha("*", mapaLinhasAProcessar);
                }
                boolean processarLinhaAtual = processarTodasAsLinhas || (listaColunas != null);
                if (processarLinhaAtual) {
                    Iterator itColunas = linha.cellIterator();
                    processarTodasAsColunas = (listaColunas != null) && (listaColunas.size() > 0)
                            && ("" + listaColunas.get(0)).equals("*");
                    while (itColunas.hasNext()) {
                        HSSFCell celula = (HSSFCell) itColunas.next();
                        int intCelulaAtual = celula.getCellNum() + 1;
                        boolean processarColunaAtual = processarTodasAsColunas
                                || ((listaColunas != null) && (listaColunas.size() > 0)
                                        && listaColunas.indexOf(new Long(intCelulaAtual)) != -1);
                        LinhaColunaListenerVo linhaColunaListenerVo = new LinhaColunaListenerVo();
                        linhaColunaListenerVo.setLinha(intLinhaAtual);
                        linhaColunaListenerVo.setColuna(intCelulaAtual);
                        linhaColunaListenerVo.setCelulaAtual(celula);
                        if (processarColunaAtual) {
                            if (celula != null) {
                                log.debug("Coluna --> " + intCelulaAtual + " para a linha --> " + intLinhaAtual
                                        + " deve ser processada...");
                                switch (celula.getCellType()) {
                                case HSSFCell.CELL_TYPE_STRING:
                                    linhaColunaListenerVo.setValorStr(celula.getStringCellValue());
                                    break;
                                case HSSFCell.CELL_TYPE_NUMERIC:
                                    linhaColunaListenerVo
                                            .setValorNumerico(new Double(celula.getNumericCellValue()));
                                    break;
                                case HSSFCell.CELL_TYPE_FORMULA:
                                    linhaColunaListenerVo.setCelulaFormula(true);
                                    linhaColunaListenerVo.setValorStrFormula(celula.getCellFormula());
                                    break;
                                case HSSFCell.CELL_TYPE_ERROR:
                                    linhaColunaListenerVo.setCelulaContemErro(true);
                                    linhaColunaListenerVo.setErro(new Byte(celula.getErrorCellValue()));
                                    break;
                                case HSSFCell.CELL_TYPE_BOOLEAN:
                                    linhaColunaListenerVo
                                            .setValorBoolean(new Boolean(celula.getBooleanCellValue()));
                                    break;
                                case HSSFCell.CELL_TYPE_BLANK:
                                    linhaColunaListenerVo.setCelulaBranca(true);
                                    linhaColunaListenerVo.setValorStr("");
                                    break;
                                }
                            } else {
                                log.warn("Clula  nula!");
                                linhaColunaListenerVo.setCelulaNula(true);
                            }
                            listaVosColunas.add(linhaColunaListenerVo);
                        } else {
                            log.debug("Coluna --> " + intCelulaAtual + " para a linha --> " + intLinhaAtual
                                    + " no deve ser processada...");
                        }
                    }
                    if (this.linhaListener != null) {
                        log.debug("Chamando o listener para a linha --> " + intLinhaAtual);
                        Collections.sort(listaVosColunas, new Comparator() {
                            public int compare(Object arg0, Object arg1) {
                                int colunaUm = ((LinhaColunaListenerVo) arg0).getColuna();
                                int colunaDois = ((LinhaColunaListenerVo) arg1).getColuna();
                                if (colunaUm < colunaDois) {
                                    return -1;
                                } else if (colunaUm > colunaDois) {
                                    return 1;
                                }
                                return 0;
                            }
                        });
                        propriedadesListenerLinha.put(LinhaListener.LISTA_VOS_LINHA, listaVosColunas);
                        continuarProcessamentoLinha = this.linhaListener.lendoLinha(intLinhaAtual,
                                propriedadesListenerLinha);
                        if (!continuarProcessamentoLinha) {
                            log.debug(
                                    "Listener retornou boolean false indicando que o processamento deve ser interrompido!");
                        }
                    } else {
                        log.debug("Listener no configurado para a linha --> " + intLinhaAtual);
                    }
                    if (this.colunaListener != null) {
                        Iterator itColunasVoListener = listaVosColunas.iterator();
                        boolean continuarProcessamentoColunasnaLinha = true;
                        while (itColunasVoListener.hasNext() && continuarProcessamentoColunasnaLinha) {
                            propriedadesListenerColuna.clear();
                            LinhaColunaListenerVo voAtual = (LinhaColunaListenerVo) itColunasVoListener.next();
                            propriedadesListenerColuna.put(ColunaListener.CHAVE_VO_COLUNA, voAtual);
                            propriedadesListenerColuna.put(ColunaListener.CHAVE_COLUNA_OBJETO_ORIGINAL_POI,
                                    voAtual.getCelulaAtual());
                            log.debug("Chamando o listener para a coluna --> " + voAtual.getColuna()
                                    + " na linha " + voAtual.getLinha());
                            continuarProcessamentoColunasnaLinha = this.colunaListener.lendoColuna(
                                    voAtual.getLinha(), voAtual.getColuna(), propriedadesListenerColuna);
                            if (!continuarProcessamentoColunasnaLinha) {
                                log.debug(
                                        "Listener de coluna retornou boolean false indicando que o processamento das colunas na linha "
                                                + voAtual.getLinha() + " deve ser interrompido!");
                            }
                        }
                    } else {
                        log.debug("Listener no configurado para processamento das colunas");
                    }
                } else {
                    log.debug("Linha --> " + intLinhaAtual + " no ser processada!");
                }
            }
        }
        log.debug("Processamento da planilha realizado com sucesso!");
    } catch (ParseException e) {
        e.printStackTrace();
        log.error("Erro ao processar a string de entrada ", e);
        throw e;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        log.error("Arquivo " + this.caminhoArquivoExcel + " no encontrado", e);
        throw e;
    } catch (IOException e) {
        e.printStackTrace();
        log.error("Erro ao abrir o arquivo " + this.caminhoArquivoExcel, e);
        throw e;
    } catch (ListenerException e) {
        e.printStackTrace();
        log.error("Erro ao processar o listener ", e);
        throw e;
    }
}

From source file:cdc.impl.datasource.office.ExcelDataSource.java

License:LGPL

private static DataColumnDefinition[] readDataModel(String sourceName, Map params)
        throws IOException, RJException {
    BufferedInputStream is = null;
    try {//  w w w.j  a v a 2  s. c o  m
        is = new BufferedInputStream(new FileInputStream((String) params.get(PARAM_FILE)));
        HSSFWorkbook wb = new HSSFWorkbook(new POIFSFileSystem(is));
        String[] sheets;
        if (params.get(PARAM_SHEET) != null) {
            sheets = new String[] { (String) params.get(PARAM_SHEET) };
        } else {
            sheets = new String[wb.getNumberOfSheets()];
            for (int i = 0; i < sheets.length; i++) {
                sheets[i] = wb.getSheetName(i);
            }
        }
        if (sheets.length == 0) {
            throw new RJException("Excel file " + params.get(PARAM_FILE) + " does not provide any sheets.");
        }
        List cols = new ArrayList();
        HSSFSheet sheet = wb.getSheet(sheets[0]);
        if (sheet == null) {
            //System.out.println("Thorwing: " + "Sheet " + sheets[0] + " is not provided by file " + params.get(PARAM_FILE));
            throw new RJException(
                    "Sheet '" + sheets[0] + "' is not provided by file " + params.get(PARAM_FILE));
        }
        HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(sheet, wb);
        //first row should provide data model
        HSSFRow row = sheet.getRow(0);
        evaluator.setCurrentRow(row);
        for (int i = 0; i < row.getPhysicalNumberOfCells(); i++) {
            HSSFCell cell = row.getCell(i);
            cols.add(new ExcelDataColumnDefinition(decodeValue(cell, evaluator),
                    DataColumnDefinition.TYPE_STRING, sourceName, i));
        }
        for (int i = 1; i < sheets.length; i++) {
            sheet = wb.getSheet(sheets[i]);
            if (sheet == null) {
                throw new RJException("Sheet '" + params.get(PARAM_SHEET) + "' is not provided by file "
                        + params.get(PARAM_FILE));
            }
            evaluator = new HSSFFormulaEvaluator(sheet, wb);
            //first row should provide data model
            row = sheet.getRow(0);
            evaluator.setCurrentRow(row);
            List localCols = new ArrayList();
            for (i = 0; i < row.getPhysicalNumberOfCells(); i++) {
                HSSFCell cell = row.getCell(i);
                DataColumnDefinition col = new ExcelDataColumnDefinition(decodeValue(cell, evaluator),
                        DataColumnDefinition.TYPE_STRING, sourceName, i);
                localCols.add(col);
            }
            List toRemove = new ArrayList();
            for (Iterator iterator = cols.iterator(); iterator.hasNext();) {
                DataColumnDefinition object = (DataColumnDefinition) iterator.next();
                if (!localCols.contains(object)) {
                    toRemove.add(object);
                }
            }
            cols.removeAll(toRemove);
        }

        return (DataColumnDefinition[]) cols.toArray(new DataColumnDefinition[] {});
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:cdc.impl.datasource.office.ExcelDataSource.java

License:LGPL

private void openFile() throws IOException, RJException {
    stream = new BufferedInputStream(new FileInputStream(getProperty(PARAM_FILE)));
    workbook = new HSSFWorkbook(new POIFSFileSystem(stream));
    iterator = new SheetsIterator(workbook,
            getProperty(PARAM_SHEET) == null ? null : new String[] { getProperty(PARAM_SHEET) });
    filesOpen = true;/*from   www.  j  a  v  a2 s. c  o m*/
    closed = false;
}

From source file:ch.elexis.core.importer.div.importers.ExcelWrapper.java

License:Open Source License

/**
 * Load a specific page of the given Excel Spreadsheet
 * /* w  w  w  . j a  va 2  s  .  com*/
 * @param file
 *            filename of the Excel file
 * @param page
 *            page to use
 * @return true on success
 * @deprecated use load(InputStream) instead
 */
@Deprecated
public boolean load(final String file, final int page) {
    try {
        fs = new POIFSFileSystem(new FileInputStream(file));
        HSSFWorkbook wb = new HSSFWorkbook(fs);
        sheet = wb.getSheetAt(page);
        return true;
    } catch (Exception ex) {
        return false;
    }
}

From source file:ch.elexis.core.importer.div.importers.ExcelWrapper.java

License:Open Source License

/**
 * Load a specific page of the given Excel Spreadsheet
 * //from  w w  w .  j a va2 s  . c o  m
 * @param bytes
 *            Excel content as byte array
 * @param page
 *            page to use
 * @return true on success
 */
public boolean load(final InputStream inputStream, final int page) {
    try {
        fs = new POIFSFileSystem(inputStream);
        HSSFWorkbook wb = new HSSFWorkbook(fs);
        sheet = wb.getSheetAt(page);
        return true;
    } catch (Exception ex) {
        return false;
    }
}

From source file:ch.javasoft.metabolic.parse.ExcelParser.java

License:BSD License

/**
 * /*from  www  . ja va 2  s  .  c o  m*/
 * @param file                  the excel file to parse
 * @param sheetIndex            0 based index of the worksheet
 * @throws FileNotFoundException   if the specified file does not exist
  * @throws IOException         if an i/o exception occurs, for instance 
  *                         caused by file access
 */
public ExcelParser(File file, int sheetIndex) throws FileNotFoundException, IOException {
    POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(file));
    mWorkbook = new HSSFWorkbook(fs);
    mSheet = mWorkbook.getSheetAt(sheetIndex);
    mFile = file;
    if (mSheet == null)
        throw new IOException("no sheet " + sheetIndex + " in excel file '" + file.getAbsolutePath() + "'");
    mSheetName = mWorkbook.getSheetName(sheetIndex);
}

From source file:ch.javasoft.metabolic.parse.ExcelParser.java

License:BSD License

protected ExcelParser(File file, String worksheet) throws FileNotFoundException, IOException {
    POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(file));
    mWorkbook = new HSSFWorkbook(fs);
    mSheet = worksheet == null ? mWorkbook.getSheetAt(0) : mWorkbook.getSheet(worksheet);
    mFile = file;//from   ww  w.j  a va  2  s  .  c  om
    if (mSheet == null)
        throw new IOException("no sheet " + (worksheet == null ? "0" : "'" + worksheet + "'")
                + " in excel file '" + file.getAbsolutePath() + "'");
    mSheetName = worksheet == null ? mWorkbook.getSheetName(0) : worksheet;
}

From source file:citibob.reports.PoiXlsWriter.java

License:Open Source License

/** @param displayTZ TimeZone to use when converting dates to Excel serial dates. */
public PoiXlsWriter(InputStream templateIn, TimeZone displayTZ) throws IOException {
    POIFSFileSystem fs = new POIFSFileSystem(templateIn);
    wb = new HSSFWorkbookExt(fs);
    xlserial = new ExcelSerialDate(displayTZ);
    templateIn.close();// w ww. ja  v a  2s  . co  m
}