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

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

Introduction

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

Prototype

public XSSFWorkbook() 

Source Link

Document

Create a new SpreadsheetML workbook.

Usage

From source file:br.com.tecsinapse.files.test.ExporterFileTest.java

License:LGPL

@DataProvider(name = "beans")
public Object[][] beans() {
    final List<FileBean> beans = FileBean.getBeans();

    //melhorar e unificar api de exportao
    final Function<Table, File> csvExport = new Function<Table, File>() {
        @Override//ww w  . j a va2  s.  c o m
        public File apply(Table table) {
            try {
                final File csv = File.createTempFile("csv", ".csv");
                csv.deleteOnExit();

                ExporterUtil.writeCsvToOutput(table, Charsets.ISO_8859_1.displayName(),
                        new FileOutputStream(csv));

                return csv;
            } catch (IOException e) {
                throw Throwables.propagate(e);
            }
        }
    };
    final Function<File, List<List<String>>> csvLines = new Function<File, List<List<String>>>() {
        @Override
        public List<List<String>> apply(File input) {
            try {
                final List<String> strings = CsvUtil.processCSV(new FileInputStream(input),
                        Charsets.ISO_8859_1);

                return FluentIterable.from(strings).transform(new Function<String, List<String>>() {
                    @Override
                    public List<String> apply(String input) {
                        return Arrays.asList(input.split(";"));
                    }
                }).toList();
            } catch (IOException e) {
                throw Throwables.propagate(e);
            }
        }
    };

    final Function<File, List<List<String>>> excelLines = new Function<File, List<List<String>>>() {
        @Override
        public List<List<String>> apply(File file) {
            try (final SpreadsheetParser<?> parser = new SpreadsheetParser<>(null, file)) {
                parser.setExporterFormatter(exporterFormatter);
                parser.setHeadersRows(0);
                return parser.getLines();
            } catch (Exception e) {
                throw Throwables.propagate(e);
            }
        }
    };

    final Function<Table, File> xlsExport = toWorkbookFunction(new Supplier<Workbook>() {
        @Override
        public Workbook get() {
            return new HSSFWorkbook();
        }
    });
    final Function<Table, File> xlsxExport = toWorkbookFunction(new Supplier<Workbook>() {
        @Override
        public Workbook get() {
            return new XSSFWorkbook();
        }
    });
    final Function<Table, File> sxlsxExport = toWorkbookFunction(new Supplier<Workbook>() {
        @Override
        public Workbook get() {
            return new SXSSFWorkbook();
        }
    });

    return new Object[][] { { beans, csvExport, csvLines, "#.#", "" },
            { beans, xlsExport, excelLines, "#.#", "" }, { beans, xlsxExport, excelLines, ".#", "" },
            { beans, sxlsxExport, excelLines, ".#", "" } };
}

From source file:br.uff.ic.kraken.extractdata.excel.ConflictingChunkData.java

public static void main(String[] args) {

    String bdName = "automaticAnalysisUpdated";
    String outputPath = "/Users/gleiph/Dropbox/doutorado/publication/TSE Manual + Automatic/TSE 2/report1.0.xlsx";

    //Excel stuff
    XSSFWorkbook wb = new XSSFWorkbook();
    XSSFSheet sheet = wb.createSheet("Data");
    int rowNumber = 0;

    XSSFRow row = sheet.createRow(rowNumber);
    XSSFCell cell = row.createCell(PROJECT_ID);
    cell.setCellValue("Project ID");

    row = sheet.createRow(rowNumber++);//from  ww  w .  jav  a 2s.c o m
    cell = row.createCell(PROJECT_NAME);
    cell.setCellValue("Project name");

    cell = row.createCell(REVISION_SHA);
    cell.setCellValue("Revision SHA");

    cell = row.createCell(FILE_NAME);
    cell.setCellValue("File name");

    cell = row.createCell(CONFLICTING_CHUNK_IDENTIFIER);
    cell.setCellValue("Conflicting chunk identifier");

    cell = row.createCell(OUTMOST_KIND_CONFLICT);
    cell.setCellValue("Kind of conflict");

    cell = row.createCell(AMOUNT_LANGUAGE_CONSTRUCTS);
    cell.setCellValue("#Language constructs");

    cell = row.createCell(DEVELOPER_DECISION);
    cell.setCellValue("Developer decision");

    cell = row.createCell(LOC_VERSION_1);
    cell.setCellValue("#LOC Version 1");

    cell = row.createCell(LOC_VERSION_2);
    cell.setCellValue("#LOC Version 2");

    cell = row.createCell(DEVELOPERS);
    cell.setCellValue("Developers");

    try (Connection connection = (new JDBCConnection()).getConnection(bdName)) {

        ProjectJDBCDAO projectDAO = new ProjectJDBCDAO(connection);
        RevisionJDBCDAO revisionDAO = new RevisionJDBCDAO(connection);
        ConflictingFileJDBCDAO conflictingFileDAO = new ConflictingFileJDBCDAO(connection);
        ConflictingChunkJDBCDAO conflictingChunkDAO = new ConflictingChunkJDBCDAO(connection);

        List<Project> projects = projectDAO.selectAnalyzedMainProjects();

        for (Project project : projects) {

            System.out.println(project.getName());

            List<Revision> revisions = revisionDAO.selectByProjectId(project.getId());
            for (Revision revision : revisions) {

                List<ConflictingFile> conflictingFiles = conflictingFileDAO
                        .selectByRevisionId(revision.getId());
                for (ConflictingFile conflictingFile : conflictingFiles) {

                    if (!conflictingFile.getName().toLowerCase().endsWith(".java")) {
                        continue;
                    }

                    List<ConflictingChunk> conflictingChunks = conflictingChunkDAO
                            .selectByConflictingFileId(conflictingFile.getId());
                    for (ConflictingChunk conflictingChunk : conflictingChunks) {

                        row = sheet.createRow(rowNumber++);
                        cell = row.createCell(PROJECT_ID);
                        cell.setCellValue(project.getId());
                        //                            System.out.print(project.getId() + ", ");

                        cell = row.createCell(PROJECT_NAME);
                        cell.setCellValue(project.getName());
                        //                            System.out.print(project.getName() + ", ");

                        cell = row.createCell(REVISION_SHA);
                        cell.setCellValue(revision.getSha());
                        //                            System.out.print(revision.getSha() + ", ");

                        cell = row.createCell(FILE_NAME);
                        cell.setCellValue(conflictingFile.getName());
                        //                            System.out.print(conflictingFile.getName() + ", ");

                        cell = row.createCell(CONFLICTING_CHUNK_IDENTIFIER);
                        cell.setCellValue(conflictingChunk.getId());
                        //                            System.out.print(conflictingChunk.getIdentifier() + ", ");

                        String generalKindConflictOutmost = conflictingChunk.getGeneralKindConflictOutmost();
                        cell = row.createCell(OUTMOST_KIND_CONFLICT);
                        String newKindConflict = replaceAttributeByVariable(generalKindConflictOutmost);

                        cell.setCellValue(newKindConflict);
                        //                            System.out.print(generalKindConflictOutmost + ", ");

                        String[] languageConstructs = generalKindConflictOutmost.split(", ");
                        cell = row.createCell(AMOUNT_LANGUAGE_CONSTRUCTS);
                        cell.setCellValue(languageConstructs.length);
                        //                                                        System.out.print(languageConstructs.length + ", ");

                        String developerDecision = conflictingChunk.getDeveloperDecision().toString();
                        cell = row.createCell(DEVELOPER_DECISION);
                        cell.setCellValue(developerDecision);
                        //                            System.out.print(developerDecision + ", ");

                        int locVersion1 = conflictingChunk.getSeparatorLine() - conflictingChunk.getBeginLine()
                                - 1;
                        int locVersion2 = conflictingChunk.getEndLine() - conflictingChunk.getSeparatorLine()
                                - 1;

                        cell = row.createCell(LOC_VERSION_1);
                        cell.setCellValue(locVersion1);

                        cell = row.createCell(LOC_VERSION_2);
                        cell.setCellValue(locVersion2);
                        //                            System.out.println(locVersion1 + ", " + locVersion2);

                        cell = row.createCell(DEVELOPERS);
                        cell.setCellValue(project.getDevelopers());

                        if (rowNumber % 10 == 0) {
                            FileOutputStream out;
                            out = new FileOutputStream(outputPath);
                            wb.write(out);
                            out.close();

                        }

                    }
                }
            }

        }

    } catch (SQLException ex) {
        Logger.getLogger(ConflictingChunkData.class.getName()).log(Level.SEVERE, null, ex);
    } catch (FileNotFoundException ex) {
        Logger.getLogger(ConflictingChunkData.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(ConflictingChunkData.class.getName()).log(Level.SEVERE, null, ex);
    }

    try {
        FileOutputStream out;
        out = new FileOutputStream(outputPath);
        wb.write(out);
        out.close();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(ConflictingChunkData.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(ConflictingChunkData.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:br.ufpa.psi.comportamente.labgame.relatorios.RelatorioJogadasExperimento.java

License:Open Source License

public InputStream relatorioOntogenese(Long idExp) throws FileNotFoundException, IOException {
    Workbook wb = new XSSFWorkbook();
    Sheet sheet = wb.createSheet("Relatrio Ontognese");

    JogadaDAO jogadaDAO = new JogadaDAO();

    jogadaDAO.beginTransaction();/*w  w  w.j a  va 2 s  . co m*/
    List<Jogada> jogadasAux = jogadaDAO.encontrarPorExperimento(idExp);
    jogadaDAO.stopOperation(false);

    ExperimentoDAO expDAO = new ExperimentoDAO();

    expDAO.beginTransaction();
    Experimento experimento = expDAO.find(Experimento.class, idExp);
    expDAO.stopOperation(false);

    JogadorDAO jogDAO = new JogadorDAO();

    jogDAO.beginTransaction();
    List<Jogador> jogadoresTotais = jogDAO.encontraPorExperimento(experimento);
    jogDAO.stopOperation(false);

    //CRIA O CABEALHO "ONTOGNESE
    int quantidadeColunas = 6;
    int quantidadeJogadoresPorCiclo = experimento.getTamanhoFilaJogadores(); //Vai pegar o valor de acordo com o experimento.
    int larguraColuna = 4600;
    int colunaAtual;
    int colunaFinalOntogenese = (quantidadeColunas * quantidadeJogadoresPorCiclo) + 1;

    // --- DEFINE AS PROPRIEDADES DAS CLULAS
    sheet.addMergedRegion(new CellRangeAddress(0, 2, 0, 0));
    sheet.addMergedRegion(new CellRangeAddress(0, 2, 1, 1));
    sheet.setColumnWidth(0, 1500);
    sheet.setColumnWidth(1, 2000);
    sheet.addMergedRegion(new CellRangeAddress(0, 1, 2, colunaFinalOntogenese));
    sheet.addMergedRegion(new CellRangeAddress(1, 2, colunaFinalOntogenese + 1, colunaFinalOntogenese + 1));
    sheet.setColumnWidth(colunaFinalOntogenese + 1, 3000);
    sheet.addMergedRegion(new CellRangeAddress(1, 3, colunaFinalOntogenese + 2, colunaFinalOntogenese + 2));
    sheet.setColumnWidth(colunaFinalOntogenese + 2, 4000);

    // --- FIM

    //for (int i = 0; i < quantidadeJogadoresPorCiclo; i++)
    //if(i == 1){
    sheet.setColumnWidth(2, larguraColuna); // Campo com o nome do participante fica nessa coluna.
    colunaAtual = 2 + quantidadeColunas;
    //} else {
    sheet.setColumnWidth((colunaAtual), larguraColuna);
    colunaAtual += quantidadeColunas;
    sheet.setColumnWidth(colunaAtual, larguraColuna);

    //}
    // ---DEFINE AS CORES DE CADA FONTE
    XSSFFont fonteBranca = (XSSFFont) wb.createFont();
    fonteBranca.setColor(new XSSFColor(Color.WHITE));
    XSSFFont fonteNegra = (XSSFFont) wb.createFont();
    fonteNegra.setColor(new XSSFColor(Color.BLACK));
    XSSFFont fonteVermelha = (XSSFFont) wb.createFont();
    fonteVermelha.setColor(new XSSFColor(Color.RED));

    // --- FIM

    // --- DEFINE ESTILOS CLULAS
    //ESTILO COLUNA LINHA
    XSSFCellStyle estiloColunaLinha = (XSSFCellStyle) wb.createCellStyle();

    estiloColunaLinha.setVerticalAlignment(VerticalAlignment.CENTER);
    estiloColunaLinha.setAlignment(CellStyle.ALIGN_CENTER);
    estiloColunaLinha.setFillForegroundColor(new XSSFColor(Color.LIGHT_GRAY));
    estiloColunaLinha.setFillPattern(CellStyle.SOLID_FOREGROUND);
    estiloColunaLinha.getFont().setBold(true);
    estiloColunaLinha.setBorderBottom(BorderStyle.MEDIUM);
    estiloColunaLinha.setBorderLeft(BorderStyle.MEDIUM);
    estiloColunaLinha.setBorderRight(BorderStyle.MEDIUM);
    estiloColunaLinha.setBorderTop(BorderStyle.MEDIUM);

    XSSFCellStyle estiloColunaColuna = (XSSFCellStyle) wb.createCellStyle();

    estiloColunaColuna.setVerticalAlignment(VerticalAlignment.CENTER);
    estiloColunaColuna.setAlignment(CellStyle.ALIGN_CENTER);
    estiloColunaColuna.getFont().setBold(true);

    //ESTILO CABEALHO
    XSSFCellStyle estiloCabecalhoColunaAB = (XSSFCellStyle) wb.createCellStyle();

    estiloCabecalhoColunaAB.setVerticalAlignment(VerticalAlignment.CENTER);
    estiloCabecalhoColunaAB.setAlignment(CellStyle.ALIGN_CENTER);
    estiloCabecalhoColunaAB.setFillForegroundColor(new XSSFColor(Color.LIGHT_GRAY));
    estiloCabecalhoColunaAB.setFillPattern(CellStyle.SOLID_FOREGROUND);
    estiloCabecalhoColunaAB.getFont().setBold(true);

    XSSFCellStyle estiloCabecalhoColunaP = (XSSFCellStyle) wb.createCellStyle();

    estiloCabecalhoColunaP.setVerticalAlignment(VerticalAlignment.CENTER);
    estiloCabecalhoColunaP.setAlignment(CellStyle.ALIGN_CENTER);
    estiloCabecalhoColunaP.setFont(fonteNegra);
    estiloCabecalhoColunaP.getFont().setBold(true);

    //ESTILO MUDANA DE CICLO
    XSSFCellStyle estiloMudancaCiclo = (XSSFCellStyle) wb.createCellStyle();
    estiloMudancaCiclo.setVerticalAlignment(VerticalAlignment.CENTER);
    estiloMudancaCiclo.setAlignment(CellStyle.ALIGN_CENTER);
    estiloMudancaCiclo.setFillForegroundColor(new XSSFColor(Color.RED));
    estiloMudancaCiclo.setFillPattern(CellStyle.SOLID_FOREGROUND);
    estiloMudancaCiclo.setFont(fonteBranca);

    //ESTILO CICLO SEM MUDANA
    XSSFCellStyle estiloCicloSemMudanca = (XSSFCellStyle) wb.createCellStyle();
    estiloCicloSemMudanca.setVerticalAlignment(VerticalAlignment.CENTER);
    estiloCicloSemMudanca.setAlignment(CellStyle.ALIGN_CENTER);
    estiloCicloSemMudanca.setFont(fonteNegra);

    //ESTILO NOME PARTICIPANTE
    XSSFCellStyle estiloNomeP = (XSSFCellStyle) wb.createCellStyle();
    estiloNomeP.setVerticalAlignment(VerticalAlignment.CENTER);
    estiloNomeP.setAlignment(CellStyle.ALIGN_CENTER);
    estiloNomeP.setBorderBottom(BorderStyle.DOTTED);
    estiloNomeP.setBorderTop(BorderStyle.DOTTED);
    estiloNomeP.setFillForegroundColor(new XSSFColor(Color.BLACK));
    estiloNomeP.setFillPattern(CellStyle.SOLID_FOREGROUND);
    estiloNomeP.setFont(fonteBranca);
    estiloNomeP.getFont().setBold(true);

    //ESTILO ESTABILIDADE
    XSSFCellStyle estiloEstabilidade = (XSSFCellStyle) wb.createCellStyle();
    estiloEstabilidade.setVerticalAlignment(VerticalAlignment.CENTER);
    estiloEstabilidade.setAlignment(CellStyle.ALIGN_CENTER);
    estiloEstabilidade.setFont(fonteVermelha);
    estiloEstabilidade.getFont().setBold(true);

    // --- FIM

    int cr = 0;

    // --- CRIA PRIMEIRA COLUNA (CABEALHO)
    XSSFRow row1 = (XSSFRow) sheet.createRow((short) cr++);

    //CRIA CLULA 1
    XSSFCell c1 = row1.createCell(0);

    c1.setCellValue("FASE");
    c1.setCellStyle(estiloCabecalhoColunaAB);

    //CRIA CLULA 2
    XSSFCell c2 = row1.createCell(1);

    c2.setCellValue("CICLO");
    c2.setCellStyle(estiloCabecalhoColunaAB);

    //CRIA CLULA 3 (ONTOGNESE)
    XSSFCell cOnto = row1.createCell(2);
    cOnto.setCellValue("ONTOGNESE");
    cOnto.setCellStyle(estiloCicloSemMudanca);

    //CRIA CLULA 'CC'
    XSSFRow row2 = (XSSFRow) sheet.createRow(1);
    XSSFCell cCC = row2.createCell(colunaFinalOntogenese + 1);
    cCC.setCellValue("CC");
    cCC.setCellStyle(estiloCicloSemMudanca);

    //CRIA CLULA 'ESTABILIDADE'
    XSSFCell cEstab = row2.createCell(colunaFinalOntogenese + 2);
    cEstab.setCellValue("ESTABILIDADE");
    cEstab.setCellStyle(estiloEstabilidade);

    // --- FIM

    int contadorCelulasCabecalho = 2;
    int contadorAcertosCultural = 0;
    XSSFRow row3 = (XSSFRow) sheet.createRow((short) 2);
    //GERA O CABEALHO DAS JOGADAS
    for (int i = 0; i < experimento.getTamanhoFilaJogadores(); i++) {
        //CRIA CLULA 3 NA LINHA 3
        XSSFCell c3 = row3.createCell(contadorCelulasCabecalho++);

        c3.setCellValue("P");
        c3.setCellStyle(estiloCabecalhoColunaP);

        //CRIA CLULA 4 NA LINHA 3
        XSSFCell c4 = row3.createCell(contadorCelulasCabecalho++);

        c4.setCellValue("Linha");
        c4.setCellStyle(estiloCabecalhoColunaP);

        //CRIA CLULA 5 NA LINHA 3
        XSSFCell c5 = row3.createCell(contadorCelulasCabecalho++);

        c5.setCellValue("Cor");
        c5.setCellStyle(estiloCabecalhoColunaP);

        //CRIA CLULA 6 NA LINHA 3
        XSSFCell c6 = row3.createCell(contadorCelulasCabecalho++);

        c6.setCellValue("Col");
        c6.setCellStyle(estiloCabecalhoColunaP);

        //CRIA CLULA 7 NA LINHA 3
        XSSFCell c7 = row3.createCell(contadorCelulasCabecalho++);

        c7.setCellValue("CI");
        c7.setCellStyle(estiloCabecalhoColunaP);

        //CRIA CLULA 8 NA LINHA 3
        XSSFCell c8 = row3.createCell(contadorCelulasCabecalho++);

        c8.setCellValue("CI Cum");
        c8.setCellStyle(estiloCabecalhoColunaP);

    }

    //VARI?VEIS INICIAIS DA ELABORAO DO RELATRIO
    int quantidadeCiclosTotais = (jogadasAux.size() / experimento.getTamanhoFilaJogadores());
    int contRowJogadas = 4;
    int contadorCiclo = 1;

    //INICIA LISTA DOS JOGADORES POR ORDEM
    List<Jogador> jogadoresAtuais = new ArrayList<>();
    int contOrdem = 1;
    for (int i = 0; i < quantidadeJogadoresPorCiclo; i++) {
        for (Jogador jgdr : jogadoresTotais) {
            if (jgdr.getOrdem() == contOrdem) {
                jogadoresAtuais.add(jgdr);
                contOrdem++;
                break;
            }
        }
    }

    //FAZ A REMOO DO(S) ELEMENTO(S) DA LISTA PRA POUPAR RECURSO EM BUSCA FUTURA
    jogadoresTotais.removeAll(jogadoresAtuais);

    //CRIA INSTNCIA CONTROLE DE PONTUAO CULTURAL
    int pontCulturalCiclo;

    //FOR (JOGADOR : JOGADORES POR CICLO)
    //CRIA LISTA DE CADA JOGADOR AT FIM DO CICLO
    for (int i = 0; i < quantidadeCiclosTotais; i++) {
        //PEGA JOGADAS DO CICLO
        List<Jogada> jogadasCiclo = new ArrayList<>();
        for (Jogada jogada : jogadasAux) {
            if (jogada.getRodada() == i + 1) {
                jogadasCiclo.add(jogada);
                if (jogadasCiclo.size() == quantidadeJogadoresPorCiclo) {
                    break;
                }
            }
        }
        //FAZ A REMOO DO(S) ELEMENTO(S) DA LISTA PRA POUPAR RECURSO EM BUSCA FUTURA
        jogadasAux.removeAll(jogadasCiclo);

        //VERIFICA SE A ORDEM MUDOU
        int contJogadoresIguais = 0;
        List<Jogada> jogadasARemover = new ArrayList<>();
        for (Jogador jogador : jogadoresAtuais) {
            for (Jogada jogada : jogadasCiclo) {
                if (jogada.getJogador().compareTo(jogador) == 0) {
                    jogador.setUltimaJogada(jogada);
                    jogador.incrementaPontuacaoRelatorio();
                    jogadasARemover.add(jogada);
                    contJogadoresIguais++;
                }
            }
        }

        jogadasCiclo.removeAll(jogadasARemover);

        boolean mudouGeracaoCiclo = false;
        if (contJogadoresIguais == quantidadeJogadoresPorCiclo) {
            //CONTINUA COM OS MESMOS JOGADORES
        } else {
            mudouGeracaoCiclo = true;
            Jogador jogadorARemover = new Jogador();
            jogadoresAtuais.remove(0);
            for (Jogador jgdr : jogadoresTotais) {
                if (jgdr.getOrdem() == contOrdem) {
                    //PEGA A PRIMEIRA POSIO PQ ESSA TEM QUE SER A NICA COM ELEMENTO
                    jgdr.setUltimaJogada(jogadasCiclo.get(0));
                    jgdr.incrementaPontuacaoRelatorio();
                    jogadoresAtuais.add(jgdr);
                    contOrdem++;
                    jogadorARemover = jgdr;
                    break;
                }
            }
            jogadoresTotais.remove(jogadorARemover);
        }
        // --- ENCERRA ETAPAS DE VERIFICAO, INICIA A POPULAO DE NOVA LINHA DO XLSX E
        //VERIFICA SE EXISTE PONTUAO CULTURAL.
        int contCellJogadas = 1;
        if (jogadoresAtuais.get(0).getUltimaJogada().getPontuacaoCultural() != 0) {
            pontCulturalCiclo = jogadoresAtuais.get(0).getUltimaJogada().getPontuacaoCultural();
            contadorAcertosCultural++;
        } else {
            pontCulturalCiclo = 0;
        }

        XSSFRow row = (XSSFRow) sheet.createRow((short) contRowJogadas);
        XSSFCell cell = row.createCell(contCellJogadas++);
        //CICLO
        if (contRowJogadas == 4 || mudouGeracaoCiclo == true) {
            //QUANDO HOUVER MUDANA DA GERAO
            cell.setCellValue(contadorCiclo++);
            cell.setCellStyle(estiloMudancaCiclo);
        } else {
            cell.setCellValue(contadorCiclo++);
            cell.setCellStyle(estiloCicloSemMudanca);
        }

        for (int j = 0; j < quantidadeJogadoresPorCiclo; j++) {

            //P
            XSSFCell cell1 = row.createCell(contCellJogadas++);
            cell1.setCellValue(jogadoresAtuais.get(j).getNome());
            cell1.setCellStyle(estiloNomeP);

            //Linha
            XSSFCell cell2 = row.createCell(contCellJogadas++);
            cell2.setCellValue(jogadoresAtuais.get(j).getUltimaJogada().getLinhaSelecionada());
            cell2.setCellStyle(estiloColunaLinha);

            //Cor
            XSSFCell cell3 = row.createCell(contCellJogadas++);
            cell3.setCellValue(jogadoresAtuais.get(j).getUltimaJogada().getCorSelecionada());
            cell3.setCellStyle(EstiloCelula.retornaEstilo(
                    jogadoresAtuais.get(j).getUltimaJogada().getCorSelecionada(), wb, fonteBranca, fonteNegra));

            //Col
            XSSFCell cell4 = row.createCell(contCellJogadas++);
            cell4.setCellValue(jogadoresAtuais.get(j).getUltimaJogada().getColunaSelecionada());
            cell4.setCellStyle(estiloColunaColuna);

            //CI
            XSSFCell cell5 = row.createCell(contCellJogadas++);
            cell5.setCellValue(jogadoresAtuais.get(j).getUltimaJogada().getPontuacaoIndividual());
            cell5.setCellStyle(estiloColunaColuna);

            //CI Cum
            XSSFCell cell6 = row.createCell(contCellJogadas++);
            cell6.setCellValue(jogadoresAtuais.get(j).getPontuacaoExibidaRelatorio());
            cell6.setCellStyle(estiloColunaColuna);
        }
        //CC
        XSSFCell cell7 = row.createCell(contCellJogadas++);
        cell7.setCellValue(pontCulturalCiclo);
        cell7.setCellStyle(estiloCabecalhoColunaAB);

        // ESTABILIDADE
        XSSFCell cell8 = row.createCell(contCellJogadas);
        cell8.setCellValue((contadorAcertosCultural * 100) / (i + 1) + "%");
        cell8.setCellStyle(estiloColunaColuna);

        contRowJogadas++;
    }

    //ESCREVE O ARQUIVO
    byte[] bytes;
    try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
        wb.write(out);
        bytes = out.toByteArray();
    }
    return new ByteArrayInputStream(bytes);
}

From source file:BUS.FileManager.java

public void exportToXLSXFile(String fileName) throws FileNotFoundException, IOException {
    XSSFWorkbook wb = new XSSFWorkbook();
    XSSFSheet sheet = wb.createSheet();//ww w.  j  a  va  2s  . c o m
    List<LichThi> Data = LichThiManager.getInstance().getDsLichThi();
    int rowNum = 0;
    // set title
    Row row = sheet.createRow(rowNum++);
    Cell cell = row.createCell(0);
    cell.setCellValue("M Lp");
    cell = row.createCell(1);
    cell.setCellValue("Tn MH");
    cell = row.createCell(2);
    cell.setCellValue("SBD");
    cell = row.createCell(3);
    cell.setCellValue("Phng");
    cell = row.createCell(4);
    cell.setCellValue("Ngy");
    cell = row.createCell(5);
    cell.setCellValue("Ca");

    // set contents
    for (LichThi lt : Data) {
        row = sheet.createRow(rowNum++);
        int cellNum = 0;

        for (int i = 0; i < 6; i++) {
            cell = row.createCell(cellNum++);
            cell.setCellValue(lt.getValueAt(i));
        }
    }

    try (FileOutputStream fos = new FileOutputStream(new File(fileName))) {
        wb.write(fos);
        fos.close();
    }
}

From source file:Business.ExcelReportCreator.java

public static int create(EcoSystem system) {

    //          Steps:-
    //          Create a Workbook.
    //          Create a Sheet.
    //          Repeat the following steps until all data is processed:
    //          Create a Row.
    //          Create Cells in a Row. Apply formatting using CellStyle.
    //          Write to an OutputStream.
    //          Close the output stream.

    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet sheet = workbook.createSheet("Customer Details");

    //Custom font style for header
    CellStyle cellStyle = sheet.getWorkbook().createCellStyle();
    Font font = sheet.getWorkbook().createFont();
    font.setBold(true);/* w ww  .j a  va  2s  . com*/
    cellStyle.setFont(font);

    int rowCount = 0;
    int columnCount1 = 0;

    //Creating header row

    String s[] = { "CUSTOMER ID", "CUSTOMER NAME", "CONTACT NO.", "EMAIL ID", "USAGE(Gallons)", "BILLING DATE",
            "TOTAL BILL($)" };
    Row row1 = sheet.createRow(++rowCount);
    for (String s1 : s) {
        Cell header = row1.createCell(++columnCount1);
        header.setCellValue(s1);
        header.setCellStyle(cellStyle);
    }

    for (Network network : system.getNetworkList()) {
        for (Enterprise enterprise : network.getEnterpriseDirectory().getEnterpriseList()) {
            if (enterprise instanceof WaterEnterprise) {
                for (Organization organization : enterprise.getOrganizationDirectory().getOrganizationList()) {
                    if (organization instanceof CustomerOrganization) {
                        for (Employee employee : organization.getEmployeeDirectory().getEmployeeList()) {
                            Customer customer = (Customer) employee;
                            Row row = sheet.createRow(++rowCount);
                            int columnCount = 0;
                            for (int i = 0; i < 7; i++) {
                                Cell cell = row.createCell(++columnCount);
                                if (i == 0) {
                                    cell.setCellValue(customer.getId());
                                } else if (i == 1) {
                                    cell.setCellValue(customer.getName());
                                } else if (i == 2) {
                                    cell.setCellValue(customer.getContactNo());
                                } else if (i == 3) {
                                    cell.setCellValue(customer.getEmailId());
                                } else if (i == 4) {
                                    cell.setCellValue(customer.getTotalUsageVolume());
                                } else if (i == 5) {
                                    if (customer.getBillingDate() != null)
                                        cell.setCellValue(String.valueOf(customer.getBillingDate()));
                                    else
                                        cell.setCellValue("Bill Not yet available");
                                } else if (i == 6) {
                                    if (customer.getTotalBill() != 0)
                                        cell.setCellValue(customer.getTotalBill());
                                    else
                                        cell.setCellValue("Bill Not yet available");
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    try (FileOutputStream outputStream = new FileOutputStream("Customer_details.xlsx")) {
        workbook.write(outputStream);
    } catch (FileNotFoundException ex) {
        JOptionPane.showMessageDialog(null, "File not found");
        return 0;
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(null, "IOException");
        return 0;
    }
    return 1;
}

From source file:business.SongExcelParser.java

public boolean songsToFile(File fileSelected, ArrayList<SongContainer> songContainerList) {
    if (fileSelected instanceof File) {
        try {/*from  w  w  w  . j a va 2 s.  co  m*/
            if (!fileSelected.exists()) {
                writeEmptyFile(fileSelected);
            }
            Workbook wb = new XSSFWorkbook();
            songsToWorkbook(wb, songContainerList);
            return writeWorkbookToFile(wb, fileSelected);
        } catch (Exception e) {
            return false;
        }
    } else {
        return false;
    }
}

From source file:cartel.DynamicDegreeCalculation.java

License:Open Source License

public void compute(Graph graph) throws FileNotFoundException, IOException {

    Map<String, Integer> weightedDegreeForOneCountryfForOneYear;

    Workbook wb = new XSSFWorkbook();
    CreationHelper createHelper = wb.getCreationHelper();
    Sheet sheet = wb.createSheet("weighted degree");
    Row row;//from w  w  w.j  a v  a 2  s.c  o  m
    Cell cell;
    Map<String, Integer> countryIndices = new TreeMap();

    int index = 0;
    for (String country : CartelDynamic.europeanCountries) {
        index++;
        countryIndices.put(country, index);
    }

    //COLUMNS HEADER
    row = sheet.createRow((short) 0);
    index = 1;
    for (int i = 1948; i < 2009; i++) {
        cell = row.createCell(index);
        index++;
        cell.setCellValue(String.valueOf(i));
    }

    //CREATING EMPTY CELLS FOR EACH ROW
    for (String country : countryIndices.keySet()) {
        row = sheet.createRow((countryIndices.get(country)));
        index = 0;
        for (int i = 1948; i <= 2009; i++) {
            row.createCell(index);
            index++;
        }
    }

    //FILLING FIRST COLUMN WITH COUNTRIES
    for (String country : countryIndices.keySet()) {
        row = sheet.getRow(countryIndices.get(country));
        row.getCell(0).setCellValue(country);
    }

    int indexYear = 1;
    for (int i = 1948; i < 2009; i++) {
        weightedDegreeForOneCountryfForOneYear = new TreeMap();
        for (Node node : graph.getNodes()) {
            String nodeLabel = node.getLabel();
            int sumDegrees = 0;

            for (Edge edge : graph.getAllEdges()) {
                if (!edge.getSource().getLabel().equals(nodeLabel)
                        & !edge.getTarget().getLabel().equals(nodeLabel)) {
                    continue;
                }
                if (edge.getSource().getLabel().equals(edge.getTarget().getLabel())) {
                    continue;
                }
                AttributeValueList attributeValueList = edge.getAttributeValues();
                for (AttributeValue attributeValue : attributeValueList) {
                    if (!attributeValue.getAttribute().getTitle().equals("freq")) {
                        continue;
                    }

                    if (((Integer) attributeValue.getStartValue()) != i) {
                        continue;
                    }
                    sumDegrees = sumDegrees + Integer.parseInt(attributeValue.getValue());
                }
            }
            sumDegrees = sumDegrees / 2;
            row = sheet.getRow(countryIndices.get(nodeLabel));
            cell = row.getCell(indexYear);
            cell.setCellValue(String.valueOf(sumDegrees));

        }
        indexYear++;
    }
    String pathFile = "D:/workbook weighted degree.xlsx";
    FileOutputStream fileOut = new FileOutputStream(pathFile);

    wb.write(fileOut);

    fileOut.close();

}

From source file:CE.CyberedgeInterface.java

public void toExcel() {

    try {//from  w w w.jav  a  2 s . com
        con = DbConnection.getConnection();
        String query = "Select * from Candidates_record";
        ps = con.prepareStatement(query);
        rs = ps.executeQuery();

        XSSFWorkbook w = new XSSFWorkbook();
        XSSFSheet ws = w.createSheet("Candidates Record");
        XSSFRow header = ws.createRow(0);
        header.createCell(0).setCellValue("ID");
        header.createCell(1).setCellValue("Name");
        header.createCell(2).setCellValue("Position");
        header.createCell(3).setCellValue("Client");
        header.createCell(4).setCellValue("Location");
        header.createCell(5).setCellValue("Contact");
        header.createCell(6).setCellValue("Email");
        header.createCell(7).setCellValue("Experience");
        header.createCell(8).setCellValue("Remark");

        ws.setColumnWidth(1, 256 * 25);
        ws.setColumnWidth(2, 256 * 25);
        ws.setColumnWidth(3, 256 * 25);
        ws.setColumnWidth(4, 256 * 25);
        ws.setColumnWidth(5, 256 * 25);
        ws.setColumnWidth(6, 256 * 25);
        ws.setColumnWidth(7, 256 * 25);
        ws.setColumnWidth(8, 256 * 25);
        ws.setColumnWidth(9, 256 * 25);
        int index = 1;
        while (rs.next()) {
            XSSFRow row = ws.createRow(index);
            row.createCell(0).setCellValue(rs.getInt("Candidate_id"));
            row.createCell(1).setCellValue(rs.getString("Name"));
            row.createCell(2).setCellValue(rs.getString("Position"));
            row.createCell(3).setCellValue(rs.getString("Client"));
            row.createCell(4).setCellValue(rs.getString("Location"));
            row.createCell(5).setCellValue(rs.getString("Contact"));
            row.createCell(6).setCellValue(rs.getString("Email"));
            row.createCell(7).setCellValue(rs.getInt("Experience"));
            row.createCell(8).setCellValue(rs.getString("Remark"));
            index++;

        }
        String file = "C:\\..\\..\\..\\..\\..\\Cyberedge\\CandidateDetails.xlsx";
        FileOutputStream fileout = new FileOutputStream(file);
        w.write(fileout);

        fileout.close();

        JOptionPane.showMessageDialog(null, "File Saved");

        ps.close();
        rs.close();
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e);
    }

}

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

License:Apache License

public void addProjektstrukturPlan(String root, AnwenderloesungRenderingContainer container,
        ZipOutputBuilder zipBuilder, LocalizationEngine localizationEngine) {

    Szenario szenario = container.getSzenario();
    SzenarioItem szenarioTree = container.getSzenarioUserData().getSzenarioTree();

    try {//from  ww w.j a v a 2  s.c  o  m
        XSSFWorkbook wb = new XSSFWorkbook();
        XSSFSheet sheet = wb.createSheet("Workbreakdownstructure_" + localizationEngine.getLanguage());
        addHeader(localizationEngine, wb, sheet);
        XSSFCellStyle ergebnisStyle = getErgebnisStyle(wb);
        XSSFCellStyle modulStyle = getModulStyle(wb);
        XSSFCellStyle defaultStyle = getDefaultStyle(wb);
        int currentRow = 1;
        List<Phase> phasen = szenario.getPhasen();
        for (Phase phase : phasen) {
            currentRow = addPhase(sheet, currentRow, phase, localizationEngine, ergebnisStyle, modulStyle,
                    defaultStyle, szenarioTree) + 1;
        }

        autosize(sheet);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        wb.write(out);
        zipBuilder.addFile(root + "/" + localizationEngine.getLanguage() + "/" + "Workbreakdownstructure_"
                + localizationEngine.getLanguage() + ".xlsx", out.toByteArray());
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
}

From source file:cherry.goods.excel.ExcelFactory.java

License:Apache License

/**
 * Excel (.xlsx) ???<br />//from  ww w .  ja v  a2s  . co m
 * 
 * @return ???Excel
 */
public static Workbook createBlankXlsx() {
    return createSheet(new XSSFWorkbook());
}