Example usage for org.apache.poi.xssf.usermodel XSSFWorkbook getSheetAt

List of usage examples for org.apache.poi.xssf.usermodel XSSFWorkbook getSheetAt

Introduction

In this page you can find the example usage for org.apache.poi.xssf.usermodel XSSFWorkbook getSheetAt.

Prototype

@Override
public XSSFSheet getSheetAt(int index) 

Source Link

Document

Get the XSSFSheet object at the given index.

Usage

From source file:at.nhmwien.schema_mapping_tool.schemaReaders.XlsxConverter.java

License:Apache License

public LinkedHashMap<String, LinkedHashMap> parseFile(InputStream inputFile) {
    LinkedHashMap<String, LinkedHashMap> fields = null;

    try {/*from   w w  w.  j  ava  2s.c  om*/

        XSSFWorkbook workbook = new XSSFWorkbook(inputFile);
        XSSFSheet sheet = workbook.getSheetAt(0);
        XSSFRow row = sheet.getRow(0);

        Iterator<Cell> cellIt = row.cellIterator();

        fields = new LinkedHashMap();

        while (cellIt.hasNext()) {
            Cell currCell = cellIt.next();

            // Ignore any non-string cells (because they are not suitable as headers)
            if (currCell.getCellType() != Cell.CELL_TYPE_STRING)
                continue;

            LinkedHashMap fieldInfo = new LinkedHashMap();
            fieldInfo.put("name", currCell.getStringCellValue());
            fieldInfo.put("subfields", null);

            fields.put(currCell.getStringCellValue(), fieldInfo);
        }

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

    return fields;
}

From source file:automatedhgl.AutomatedHGL.java

public static void main(String[] args) {

    try {//w w  w. j  av a  2s.  c o m

        FileInputStream excelFile = new FileInputStream(new File(INFILE_NAME));

        //create workbook instance holding reference to .xlsx file
        XSSFWorkbook workbook = new XSSFWorkbook(excelFile);

        //get first desired sheet from the workbook
        XSSFSheet sheet = workbook.getSheetAt(0);

        //create workbook instance to output excel file
        XSSFWorkbook workbookHGL = new XSSFWorkbook();

        //create sheet in output excel file
        XSSFSheet sheetHGL = workbookHGL.createSheet("HGL");

        //iterate through each row one by one
        Iterator<Row> rowiterator = sheet.iterator();

        while (rowiterator.hasNext()) {
            Row row = rowiterator.next();

            //for each row, iterate through all the columns
            Iterator<Cell> cellIterator = row.cellIterator();

            while (cellIterator.hasNext()) {

                Cell cell = cellIterator.next();

                if (row.getRowNum() > 7 && count < 23) //to filter column headings
                {

                    //check the cell type and format accordingly
                    switch (cell.getCellType()) {
                    case Cell.CELL_TYPE_NUMERIC:
                        count++;

                        //assign get value to correct variable
                        if (count == 1) {
                            InletStr = cell.getNumericCellValue();
                        } else if (count == 2) {
                            OutWSE = cell.getNumericCellValue();
                        }

                        System.out.print(cell.getNumericCellValue() + " (" + count + ") ");
                        break;

                    case Cell.CELL_TYPE_STRING:
                        count++;

                        /*//assign get value to correct variable
                        if( count == 1 ){InletStr = cell.getStringCellValue();}*/

                        System.out.print(cell.getStringCellValue() + " (" + count + ") ");
                        break;

                    case Cell.CELL_TYPE_FORMULA:
                        count++;

                        /*//assign get value to correct variable
                        if( count == 1 ){InletStr = cell.getCachedFormulaResultType();}*/

                        System.out.print(cell.getCachedFormulaResultType() + " (" + count + ") ");
                        break;
                    }
                }

                else {
                    count = 0; //reset the count at the end of the row
                }

            }

            System.out.println("return");
        }

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

    //Output Excel file

    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet sheet = workbook.createSheet("Datatypes in Java");
    Object[][] datatypes = { { "Datatype", "Type", "Size(in bytes)" }, { "int", "Primitive", 2 },
            { "float", "Primitive", 4 }, { "double", "Primitive", 8 }, { "char", "Primitive", 1 },
            { "String", "Non-Primitive", "No fixed size" } };

    int rowNum = 0;
    System.out.println("Creating excel");

    for (Object[] datatype : datatypes) {
        Row row = sheet.createRow(rowNum++);
        int colNum = 0;
        for (Object field : datatype) {
            Cell cell = row.createCell(colNum++);
            if (field instanceof String) {
                cell.setCellValue((String) field);
            } else if (field instanceof Integer) {
                cell.setCellValue((Integer) field);
            }
        }
    }

    try {
        FileOutputStream outputStream = new FileOutputStream(FILE_NAME);
        workbook.write(outputStream);
        workbook.close();

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

    System.out.print(InletStr + " ");
    System.out.print(OutWSE + " ");
    System.out.println("HGL Done");

}

From source file:be.thomasmore.service.FileUploadServiceImp1.java

@Override
public void handleFileUpload(FileUploadEvent event) {
    clearVars();/*from  ww w.  j  a v a 2  s .c o  m*/
    InputStream file;
    XSSFWorkbook workbook = null;
    try {
        //geupload excel bestand inlezen
        file = event.getFile().getInputstream();
        workbook = new XSSFWorkbook(file);
        XSSFSheet sheet = workbook.getSheetAt(0);

        //de excell overlopen en de gegevens eruit halen
        //klas ophalen
        int i = 0;
        XSSFRow row = sheet.getRow(i++);
        klas.setNaam(row.getCell(1).getStringCellValue());// =>naam klas (bv 5a)
        //vak ophalen
        row = sheet.getRow(i++);
        vak.setNaam(row.getCell(1).getStringCellValue());// => naam vak (bv java)
        //test ophalen
        row = sheet.getRow(i++);
        test.setNaam(row.getCell(1).getStringCellValue()); // => naam test
        row = sheet.getRow(i++);
        test.setTotaal((int) row.getCell(1).getNumericCellValue());// => totaal test
        //vak.setTesten(new ArrayList<Test>(test));
        //test.setVak(vak);
        i += 2;
        //studenten +scores ophalen
        while (i <= sheet.getLastRowNum()) {
            row = sheet.getRow(i++);
            Student student = new Student();
            student.setStudentennummer(String.valueOf((int) row.getCell(0).getNumericCellValue()));
            student.setNaam(row.getCell(1).getStringCellValue());
            Score score = new Score();
            score.setKlas(klas);
            score.setStudent(student);
            score.setTest(test);
            score.setScore((int) row.getCell(2).getNumericCellValue());
            scores.add(score);
        }
        test.setScores(scores);
        klas.setScores(scores);

        // klas.setStudenten(studenten);
    } catch (IOException e) {
        // facesContext
        //   .addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error reading file" + e, null));
        e.printStackTrace();
    }
}

From source file:br.com.bb.intranet.supermt.pf.desembolso.service.ImportaDados.java

/**
 *
 * @param planilha objeto do tipo Planilha que contm todos os dados
 * necessrios para facilitar a operao na planilha
 *///from w  w  w .  j  ava2s  . co  m
public void processaPlanilha(Planilha planilha) throws NegocioException {
    List<Desembolso> dadosParaSalvar = new ArrayList();
    int linha = 0;
    Double d;
    try {

        //cria um workbook = planilha toda com todas as abas
        XSSFWorkbook workbook = new XSSFWorkbook(planilha.getFile());

        //recuperamos apenas a aba mandada
        XSSFSheet sheet = workbook.getSheetAt(planilha.getNumeroDaPlanilha() - 1);

        //retorna todas as linhas da planilha selecioada 
        Iterator<Row> rowIterator = sheet.iterator();

        //varre todas as linhas da planilha selecionada
        while (rowIterator.hasNext() && linha < planilha.getUltimaLinha()) {
            linha++;

            //recebe cada linha da planilha
            Row row = rowIterator.next();

            //andar as linhas que sero ignoradas no incio
            if (row.getRowNum() < planilha.getUltimaLinha()) {
                continue;
            }

            //pegamos todas as celulas desta linha
            Iterator<Cell> cellIterator = row.iterator();

            //responsavel por definir qual coluna esta sendo trabalhada no intante
            int coluna = 1;

            Cell cell;

            Desembolso desembolso = new Desembolso();
            //varremos todas as celulas da linha atual
            while (cellIterator.hasNext()) {
                //criamos uma celula
                cell = cellIterator.next();

                //TODO O CDIGO DE PERSISTENCIA AQUI!!

                switch (coluna) {
                case ColunasDesembolso.GRUPO:
                    desembolso.setGrupo(cell.getStringCellValue());
                    break;
                case ColunasDesembolso.PREFIXO_SUPER_INTENDENCIA:
                    cell.setCellType(Cell.CELL_TYPE_STRING);
                    desembolso.setPrefixoSuperintendencia(cell.getStringCellValue());
                    break;
                case ColunasDesembolso.NOME_SUPER_INTENDENCIA:
                    cell.setCellType(Cell.CELL_TYPE_STRING);
                    desembolso.setNomeSuperintendencia(cell.getStringCellValue());
                    break;
                case ColunasDesembolso.PREFIXO_REGIONAL:
                    cell.setCellType(Cell.CELL_TYPE_STRING);
                    desembolso.setPrefixoRegional(cell.getStringCellValue());
                    break;
                case ColunasDesembolso.NOME_AGENCIA:
                    cell.setCellType(Cell.CELL_TYPE_STRING);
                    desembolso.setNomeAgencia(cell.getStringCellValue());
                    break;
                case ColunasDesembolso.ORCAMENTO_PROPOSTO_ACUMULADO:
                    desembolso
                            .setOrcamentoPropostoAcumulado(this.doubleToBigDecimal(cell.getNumericCellValue()));
                    break;
                case ColunasDesembolso.REALIZADO_ATUAL:
                    desembolso.setRealizadoAtual(this.doubleToBigDecimal(cell.getNumericCellValue()));
                    break;
                case ColunasDesembolso.PERCENTUAL_ATINGIMENTO_UM:
                    desembolso.setPercentualAtingimentoUm(this.doubleToBigDecimal(cell.getNumericCellValue()));
                    break;
                case ColunasDesembolso.REALIZADO_D_MENOS_UM:
                    desembolso.setRealizadoDmenosUm(this.doubleToBigDecimal(cell.getNumericCellValue()));
                    break;
                case ColunasDesembolso.NECESSIDADE_DIA_MENOS_UM:
                    cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                    desembolso.setNecessidadeDiaDmenosUm(this.doubleToBigDecimal(cell.getNumericCellValue()));
                    break;
                case ColunasDesembolso.META_CONTATOS_ACUMULADA:
                    cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                    desembolso.setMetaContatosAcumulada(this.doubleToBigDecimal(cell.getNumericCellValue()));
                    break;
                case ColunasDesembolso.REALIZADO_CONTATOS_MES:
                    cell.setCellType(cell.CELL_TYPE_NUMERIC);
                    desembolso.setRealizadoContatosMes(this.doubleToBigDecimal(cell.getNumericCellValue()));
                    break;
                case ColunasDesembolso.PERCENTUAL_ATINGIMENTO_CONTATOS:
                    cell.setCellType(cell.CELL_TYPE_NUMERIC);
                    desembolso.setPercentualAtingimentoContatos(
                            this.doubleToBigDecimal(cell.getNumericCellValue()));
                    break;
                case ColunasDesembolso.CONTATOS_D_MENOS_UM:
                    cell.setCellType(cell.CELL_TYPE_NUMERIC);
                    desembolso.setContatosDmenosUm(this.doubleToBigDecimal(cell.getNumericCellValue()));
                    break;
                case ColunasDesembolso.CONTATOS_D_MENOS_DOIS:
                    cell.setCellType(cell.CELL_TYPE_NUMERIC);
                    desembolso.setContatosDmenosDois(this.doubleToBigDecimal(cell.getNumericCellValue()));
                    break;
                case ColunasDesembolso.PREFIXO_REPETE:
                    cell.setCellType(Cell.CELL_TYPE_STRING);
                    desembolso.setPrefixoRepete(cell.getStringCellValue());
                    break;
                case ColunasDesembolso.AGENCIA_REPETE:
                    cell.setCellType(Cell.CELL_TYPE_STRING);
                    desembolso.setAgenciaRepete(cell.getStringCellValue());
                    break;
                case ColunasDesembolso.CODIDGO_CARTEIRA:
                    cell.setCellType(Cell.CELL_TYPE_STRING);
                    desembolso.setCodigoCarteira(cell.getStringCellValue());
                    break;
                case ColunasDesembolso.CARTEIRA:
                    cell.setCellType(Cell.CELL_TYPE_STRING);
                    desembolso.setCarteira(cell.getStringCellValue());
                    break;
                case ColunasDesembolso.ORCAMENTO_PROPORCIONAL_ACUMULADO_DOIS:
                    cell.setCellType(cell.CELL_TYPE_NUMERIC);
                    desembolso.setOrcamentoProporcionalAcumuladoDois(
                            this.doubleToBigDecimal(cell.getNumericCellValue()));
                    break;
                case ColunasDesembolso.REALIZADO_ATUAL_DOIS:
                    cell.setCellType(cell.CELL_TYPE_NUMERIC);
                    desembolso.setRealizadoAtualDois(this.doubleToBigDecimal(cell.getNumericCellValue()));
                    break;
                case ColunasDesembolso.PERCENTUAL_ATINGIMENTO_DOIS:
                    cell.setCellType(cell.CELL_TYPE_NUMERIC);
                    desembolso
                            .setPercentualAgintimentoDois(this.doubleToBigDecimal(cell.getNumericCellValue()));
                    break;
                case ColunasDesembolso.META_CONTATOS_ACUMULADA_DOIS:
                    cell.setCellType(cell.CELL_TYPE_NUMERIC);
                    desembolso
                            .setMetaContatosAcumuladaDois(this.doubleToBigDecimal(cell.getNumericCellValue()));
                    break;
                case ColunasDesembolso.REALIZADO_CONTATOS_MES_DOIS:
                    cell.setCellType(cell.CELL_TYPE_NUMERIC);
                    desembolso.setRealizadoContatosMesDois(this.doubleToBigDecimal(cell.getNumericCellValue()));
                    break;
                case ColunasDesembolso.PERCENTUAL_ATINGIMENTO_CONTATOS_DOIS:
                    cell.setCellType(cell.CELL_TYPE_NUMERIC);
                    desembolso.setPercentualAtingimentoContatosDois(
                            this.doubleToBigDecimal(cell.getNumericCellValue()));
                    break;
                }

                System.out.println("valor = " + cell.toString());

                coluna++;
            }
            dadosParaSalvar.add(desembolso);
        }
        this.salvar(dadosParaSalvar);

    } catch (FileNotFoundException ex) {
        throw new NegocioException("Arquivo com Erro Tente novamente!!");
    } catch (IOException ex) {
        throw new NegocioException("Arquivo com Erro Tente novamente!!");
    }
}

From source file:BUS.FileManager.java

public Sheet readXLSXFile(File f) throws FileNotFoundException, IOException, InvalidFormatException {
    InputStream ExcelFileToRead = new FileInputStream(f);
    //System.out.println(f.getName());
    XSSFWorkbook wb = (XSSFWorkbook) WorkbookFactory.create(ExcelFileToRead);
    XSSFSheet sheet = wb.getSheetAt(0);
    return sheet;
}

From source file:ch.admin.isb.hermes5.business.userszenario.projektstrukturplan.ProjektstrukturplanGeneratorExcelTest.java

License:Apache License

private String buildProjektstrukturPlan(Szenario szenario) throws IOException {
    ZipOutputBuilder zipBuilder = new ZipOutputBuilder();

    AnwenderloesungRenderingContainer container = new AnwenderloesungRenderingContainer("model", szenario,
            new SzenarioUserData(), Arrays.asList("de"), true, true, true, true);

    projektstrukturplanGeneratorExcel.addProjektstrukturPlan("workbreakdownstructure", container, zipBuilder,
            new LocalizationEngine(projektstrukturplanGeneratorExcel.translationRepository, "model", "de"));

    byte[] result = zipBuilder.getResult();
    ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(result));
    ZipEntry nextEntry;//from ww w.  j  a  va  2 s . c  om

    while ((nextEntry = zipInputStream.getNextEntry()) != null) {
        assertEquals(nextEntry.getName(), "workbreakdownstructure/de/Workbreakdownstructure_de.xlsx");
        byte[] byteArray = zipUtil.readZipEntry(zipInputStream);
        java.io.FileOutputStream fileOutputStream = new java.io.FileOutputStream(
                "target/projektstrukturplan.xlsx");
        fileOutputStream.write(byteArray);
        fileOutputStream.close();
        assertNotNull(byteArray);
        XSSFWorkbook wb = new XSSFWorkbook(new ByteArrayInputStream(byteArray));
        XSSFSheet sheet = wb.getSheetAt(0);
        ByteArrayOutputStream out2 = new ByteArrayOutputStream();
        PrintStream out = new PrintStream(out2);

        for (Row row : sheet) {
            out.print("|");
            // assertTrue("" + row.getLastCellNum(), row.getLastCellNum() < 3);
            for (Cell cell : row) {
                out.print(cell.getStringCellValue());
                out.print("|");
            }
            out.println("");
        }
        return new String(out2.toByteArray());
    }
    throw new AssertionError("workbook not found");
}

From source file:ch.bfh.lca._15h.library.export.ExportToExcel.java

/***
 * Prototype function. Not yet functional.
 * Allow to generate an age pyramid graphic in Excel by using an existing Excel Template.
 * @param language Language of the label in the Excel file
 * @param rows Arrays of rows to include in the listing
 * @param excelFilePath Path of the outputed file
 * @throws FileNotFoundException//w w  w .j  av  a  2s  . co  m
 * @throws IOException
 * @throws InvalidFormatException 
 */
public static void exportToAgePyramid(Translation.TRANSLATION_LANGUAGE language, GenericResultRow[] rows,
        String excelFilePath) throws FileNotFoundException, IOException, InvalidFormatException {
    //open template
    URL url = Translation.class.getClassLoader()
            .getResource("ch/bfh/lca/_15h/library/export/template/alter-pyramide-v2.xlsx");
    //Workbook wb = WorkbookFactory.create(new File(url.getPath()));
    XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(new File(url.getPath())));

    Sheet sheet = wb.getSheetAt(0);

    //http://www.programming-free.com/2012/12/create-charts-in-excel-using-java.html
    //https://poi.apache.org/spreadsheet/quick-guide.html#NewWorkbook
    Row row;
    Cell cell;

    for (int i = 0; i < 20; i++) {
        row = sheet.getRow(i + 1);
        if (row == null) {
            row = sheet.createRow(i + 1);
        }

        for (int j = 0; j < 3; j++) {
            cell = row.getCell(j);
            if (cell == null) {
                cell = row.createCell(j);
            }

            switch (j) {
            case 0:
                cell.setCellValue(i);
                break;
            case 1:
                cell.setCellValue(i * j * -1);
                break;
            case 2:
                cell.setCellValue(i * j);
                break;
            }
        }
    }

    //redefine data range
    //http://thinktibits.blogspot.ch/2014/09/Excel-Insert-Format-Table-Apache-POI-Example.html
    XSSFSheet sheet1 = wb.getSheetAt(0);
    XSSFTable table = sheet1.getTables().get(0);
    CTTable cttable = table.getCTTable();

    AreaReference my_data_range = new AreaReference(new CellReference(0, 0), new CellReference(20, 2));
    /* Set Range to the Table */
    cttable.setRef(my_data_range.formatAsString());
    // cttable.setDisplayName("DATEN");      /* this is the display name of the table */
    //cttable.setName("test");    /* This maps to "displayName" attribute in &lt;table&gt;, OOXML */
    //cttable.setId(1L); //id attribute against table as long value

    /*
    //redefine data range
    Name rangeCell = wb.getName("DATEN");
    //Set new range for named range 
    //String reference = sheetName + "!$C$" + (deface + 1) + ":$C$" + (rowNum + deface);
    String reference = sheet.getSheetName() + "!$A$2:$C$20";
    //Assigns range value to named range
    rangeCell.setRefersToFormula(reference);
    */

    //write to the file
    FileOutputStream fileOut = new FileOutputStream(excelFilePath);
    wb.write(fileOut);
    fileOut.close();
    wb.close();
}

From source file:clases.excel.EXCELreader.java

private void prepareList(String path) {

    excelString = "";
    listaEXCEL = new ArrayList<>();
    int sw = 0;//0 no,1 si, 2 ready
    XSSFWorkbook workbook;

    try {/*from   w  w  w . ja  va  2s  .co m*/
        //Create Workbook instance holding reference to .xlsx file
        workbook = new XSSFWorkbook(new FileInputStream(new File(path)));

        //Get first/desired sheet from the workbook
        XSSFSheet sheet = workbook.getSheetAt(0);

        //Iterate through each rows one by one
        Iterator<Row> rowIterator = sheet.iterator();
        while (rowIterator.hasNext()) {
            String[] linea = new String[parametros];
            Row row = rowIterator.next();
            //For each row, iterate through all the columns
            Iterator<Cell> cellIterator = row.cellIterator();

            //  if (rowcont2 ==16) {
            //                excelString += ++rowcont + "***";
            int rowcont = 0;
            while (cellIterator.hasNext()) {

                Cell cell = cellIterator.next();

                //JOptionPane.showMessageDialog(null, "Tipo *" + cell.getCellType() + "*");
                //Check the cell type and format accordingly
                switch (cell.getCellType()) {
                case Cell.CELL_TYPE_NUMERIC:
                    //leyendo tabla
                    if (sw == 2) {
                        Double d = cell.getNumericCellValue();//String.format("%d", d.intValue())
                        excelString += ((d % 1 != 0) ? d.toString() : d.toString()) + "\t";
                        linea[rowcont++] = ((d % 1 != 0) ? d.toString() : d.toString());
                    }
                    break;

                case Cell.CELL_TYPE_STRING:
                    // JOptionPane.showMessageDialog(null, "String *" + cell.getStringCellValue().trim() + "*");
                    if (sw == 0) {
                        if (cell.getStringCellValue().trim().equals(init_detalle)) {
                            sw = 1;
                        }
                    }
                    //leyendo tabla
                    if (sw == 2) {
                        excelString += cell.getStringCellValue() + "\t";
                        linea[rowcont++] = cell.getStringCellValue();
                    }
                    break;

                case Cell.CELL_TYPE_BLANK:
                    //si estaba leyendo tabla, pero encuentra vacio
                    //  termina de leer la tabla
                    if (rowcont == 0 && sw == 2) {
                        sw = 4;
                    }
                    break;
                case Cell.CELL_TYPE_FORMULA:
                    //leyendo tabla
                    if (sw == 2) {
                        Double d = cell.getNumericCellValue();
                        excelString += ((d % 1 != 0) ? d.toString() : d.toString()) + "\t";
                        linea[rowcont++] = ((d % 1 != 0) ? d.toString() : d.toString());
                    }
                    break;
                }
                //si ya es 1 termina el ciclo, para iniciar el detalle
                //  en la siguiente linea
                if (sw == 1) {
                    sw = 2;
                    break;
                }
                //si ya no leera mas tabla, termina de leer la row
                if (sw == 4) {
                    break;
                }
            }
            //guarda si esta leyendo tabla
            if (sw == 2 && linea[0] != null) {
                listaEXCEL.add(linea);
                excelString += "\n";
            }
            //termino de leer la tabla, cierra todo
            if (sw == 4) {
                break;
            }

            //   }
        }
        int as = 0;
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:classes.CLASSEDETEST.java

public static void main(String[] args) throws FileNotFoundException, IOException {

    //        DataControle dt = new DataControle();
    //        //from ww w. j av a 2  s .  c o  m
    //        LocalDate x = LocalDate.parse("10/10/1991", dt.getFormatador());
    //        
    //        System.out.println(x.toString());
    //        
    //        System.exit(0);

    IOExcel io = new IOExcel("G:\\Pasta Eng\\xccx.xlsx");
    io.init();
    io.lerExcel();

    ControleTotal c = new ControleTotal();

    c.setListVendas(io.getListVendas());

    c.separarDados();

    System.out.println(c.produtoMaisVendido());

    System.exit(0);

    String file = "G:\\Pasta Eng\\ModeloDeCompra.xlsx";

    FileInputStream fis = new FileInputStream(new File(file));

    //create workbook instance

    XSSFWorkbook wb = new XSSFWorkbook(file);

    XSSFSheet sheet = wb.getSheetAt(0);

    //List<String> list = new ArrayList<>();

    List<List<String>> matriz = new ArrayList<>();

    int cont;

    List<String> l = new ArrayList<>();
    for (Row row : sheet) {

        for (Cell cell : row) {
            l.add(cell.getStringCellValue().trim().toLowerCase());
        }
        break;

        //matriz.add(list);
    }

    Comprador c = new Comprador();

    Produto p = new Produto();

    p.setNome(l.get(5));
    p.setMarca(l.get(6));
    p.setQtdTamanho_P(Integer.parseInt(l.get(7)));
    p.setQtdTamanho_M(Integer.parseInt(l.get(8)));
    p.setQtdTamanho_G(Integer.parseInt(l.get(9)));
    p.setGrupo(Integer.parseInt(l.get(10)));
    p.setValor(Double.parseDouble(l.get(11)));

    System.out.println("Produto:\n");

    System.out.println(p.getNome());
    System.out.println(p.getMarca());
    System.out.println(p.getQtdTamanho_P());
    System.out.println(p.getQtdTamanho_M());
    System.out.println(p.getQtdTamanho_G());
    System.out.println(p.getGrupo());
    System.out.println(p.getValor());

    System.out.println("Total De Produtos : " + p.getQuantidadeTotalProduto());

}

From source file:classes.IOExcel.java

public boolean lerExcel() {

    try {//from   w  w  w.java 2s.c  o  m

        FileInputStream fis = new FileInputStream(this.getFileExcel());

        XSSFWorkbook wb = new XSSFWorkbook(fis);
        XSSFSheet sheet = wb.getSheetAt(0);

        for (Row row : sheet) {

            List<String> list = new ArrayList<>();

            for (Cell cell : row) {
                list.add(cell.getStringCellValue().trim());
            }

            if (list.size() >= 15) {

                Vendas venda = new Vendas();

                //Vendedor
                venda.setNomeVendedor(list.get(0));

                //Comprador
                venda.setNomeComprador(list.get(1));
                venda.setSexoComprador(list.get(2));
                venda.setEstadoComprador(list.get(3));
                venda.setDataNascimentoComprador(
                        LocalDate.parse(list.get(4), new DataControle().getFormatador()));

                //Produto
                venda.setNomeProduto(list.get(5));
                venda.setMarcaProduto(list.get(6));

                venda.setQtdTamanho_P_Produto(Integer.parseInt(list.get(7)));
                venda.setQtdTamanho_M_Produto(Integer.parseInt(list.get(8)));
                venda.setQtdTamanho_G_Produto(Integer.parseInt(list.get(9)));

                venda.setGrupoProduto((Integer.parseInt(list.get(10))));
                venda.setValorProduto(Double.parseDouble(list.get(11)));

                //Pagamento
                venda.setTipoPagamento(Boolean.parseBoolean(list.get(12)));
                venda.setDebOrCredPagamento(list.get(13));
                venda.setBandeiraCartaoPagamento(list.get(14));
                venda.setNumeroParcelasPagamento(Integer.parseInt(list.get(15)));

                this.getListVendas().add(venda);
                this.numeroDeRegistros++;
            }
        }

        return true;

    } catch (Exception ex) {
        ex.printStackTrace();
        return false;
    }

}