Salvar dados de uma tbela em Excel

3 respostas
G

boa noite pessoal

estou na reta final de meu TCC mas eu queria colocar só um detalhe.
estou usando um método que pegar os dados de minha jTable e cria uma tabela no Excel.
o método é este:

public void exportarExcel() {
        JFileChooser jf = new JFileChooser();
        jf.setDialogType(JFileChooser.SAVE_DIALOG);
        jf.setOpaque(false);
        jf.showDialog(null, "Salvar");
        if (jf.getSelectedFile() != null) {
            String caminho = jf.getSelectedFile().getAbsolutePath();

            //verifica se a extensão do arquivo é correta
            if (Arquivo.obterExtensao(caminho).equals("")) {
                caminho += ".xls";
            } else {
                if (Arquivo.obterExtensao(caminho).equals("xlsx")) {
                    String novoCaminho = caminho.split(".xlsx")[0] + ".xls";
                    caminho = novoCaminho;
                }
            }

            File destino = new File(caminho);
            if (!destino.exists()) { //o erro está aqui.....!!!!!!!!!!!!
                criarArquivoExcel(destino);
            } else {
                if (JOptionPane.showConfirmDialog(null,
                        "O arquivo já existe.\n"
                        + "Deseja substituir o arquivo existente?",
                        "Aviso!", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                    destino.delete();
                    criarArquivoExcel(destino);
                }
            }
        }
    }

    private void criarArquivoExcel(File destino) {
        try {
            HSSFWorkbook workbook = new HSSFWorkbook();
            FileOutputStream stream = new FileOutputStream(destino);


            HSSFSheet sheet = workbook.createSheet("Lista de Usuários");

            //define a largura das colunas
            sheet.setColumnWidth(0, (short) 3900);
            sheet.setColumnWidth(1, (short) 3375);
            sheet.setColumnWidth(2, (short) 3750);
            sheet.setColumnWidth(3, (short) 3900);



            HSSFCellStyle estiloCabecalho = workbook.createCellStyle();
            HSSFFont fonteCabecalho = workbook.createFont();
            fonteCabecalho.setFontHeightInPoints((short) 4);
            fonteCabecalho.setFontName("Consolas");
            fonteCabecalho.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            fonteCabecalho.setItalic(true);
            estiloCabecalho.setFont(fonteCabecalho);
            estiloCabecalho.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            HSSFRow firstRow = sheet.createRow(0);

            HSSFCell cell = firstRow.createCell(0);
            cell.setCellStyle(estiloCabecalho);
            //cell.setCellValue(FramePrincipal.getUsuarioLogado().getNome());
            HSSFCellStyle firstRowStyle = workbook.createCellStyle();
            firstRowStyle.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);

            Region region = new Region(0, (short) 0, 1, (short) 3);
            sheet.addMergedRegion(region);

            //cria a linha com os nomes das colunas
            HSSFRow secondRow = sheet.createRow(2);
            //cria o estilo para essa linha
            HSSFCellStyle secondRowStyle = workbook.createCellStyle();
            HSSFFont secondRowFont = workbook.createFont();
            secondRowFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            secondRowFont.setItalic(true);
            secondRowStyle.setFont(secondRowFont);
            secondRowStyle.setBorderBottom(HSSFCellStyle.BORDER_THICK);
            secondRowStyle.setBorderLeft(HSSFCellStyle.BORDER_THICK);
            secondRowStyle.setBorderRight(HSSFCellStyle.BORDER_THICK);
            secondRowStyle.setBorderTop(HSSFCellStyle.BORDER_THICK);




            for (int i = 0; i < tblconsulta.getColumnCount(); i++) {
                HSSFCell localCell = secondRow.createCell(i);
                localCell.setCellValue(tblconsulta.getColumnName(i));
                localCell.setCellStyle(secondRowStyle);
            }

            HSSFCellStyle styleRows = workbook.createCellStyle();
            styleRows.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            styleRows.setBorderTop(HSSFCellStyle.BORDER_THIN);
            styleRows.setBorderRight(HSSFCellStyle.BORDER_THIN);
            styleRows.setBorderBottom(HSSFCellStyle.BORDER_THIN);

            //insere os dados
            for (int i = 0; i < tblconsulta.getRowCount(); i++) {
                HSSFRow row = sheet.createRow(i + 3);
                for (int y = 0; y < tblconsulta.getColumnCount(); y++) {
                    HSSFCell c = row.createCell(y);
                    c.setCellValue(tblconsulta.getValueAt(i, y).toString());
                    c.setCellStyle(styleRows);
                }
            }

            HSSFCellStyle lastRowStyle = workbook.createCellStyle();
            lastRowStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            lastRowStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
            lastRowStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
            lastRowStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            HSSFFont font = workbook.createFont();
            font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            lastRowStyle.setFont(font);
            HSSFRow lastRow = sheet.createRow(tblconsulta.getRowCount() + 4);
            HSSFRow lastRow1 = sheet.createRow(tblconsulta.getRowCount() + 5);
            HSSFRow lastRow2 = sheet.createRow(tblconsulta.getRowCount() + 6);
            HSSFRow lastRow3 = sheet.createRow(tblconsulta.getRowCount() + 7);
            HSSFRow lastRow4 = sheet.createRow(tblconsulta.getRowCount() + 8);
            HSSFRow lastRow5 = sheet.createRow(tblconsulta.getRowCount() + 9);
            HSSFRow lastRow6 = sheet.createRow(tblconsulta.getRowCount() + 10);

            HSSFCell cell1 = lastRow.createCell(0);
            cell1.setCellStyle(lastRowStyle);
            cell1.setCellValue("Total de Horas Diurnas:");

            HSSFCell cell2 = lastRow.createCell(1);
            cell2.setCellStyle(lastRowStyle);
            cell2.setCellValue(String.format(txtHorasDiurnas.getText()));



            HSSFCell cell3 = lastRow1.createCell(0);
            cell3.setCellStyle(lastRowStyle);
            cell3.setCellValue("Total de Horas Noturnas:");

            HSSFCell cell4 = lastRow1.createCell(1);
            cell4.setCellStyle(lastRowStyle);
            cell4.setCellValue(txtHorasNotunas.getText());

            HSSFCell cell5 = lastRow2.createCell(0);
            cell5.setCellStyle(lastRowStyle);
            cell5.setCellValue("Total de Horas Negativas:");

            HSSFCell cell6 = lastRow2.createCell(1);
            cell6.setCellStyle(lastRowStyle);
            cell6.setCellValue(txtHorasNegativas.getText());

            HSSFCell cell7 = lastRow3.createCell(0);
            cell7.setCellStyle(lastRowStyle);
            cell7.setCellValue("Total de Horas Extras:");

            HSSFCell cell8 = lastRow3.createCell(1);
            cell8.setCellStyle(lastRowStyle);
            cell8.setCellValue(txtHorasExtras.getText());
            workbook.write(stream);


            HSSFCell cell9 = lastRow4.createCell(0);
            cell9.setCellStyle(lastRowStyle);
            cell9.setCellValue("Total de Horas Extras Noturnas:");

            HSSFCell cell10 = lastRow4.createCell(1);
            cell10.setCellStyle(lastRowStyle);
            cell10.setCellValue(txtHorasExtrasNoturnas.getText());

            HSSFCell cell11 = lastRow5.createCell(0);
            cell11.setCellStyle(lastRowStyle);
            cell11.setCellValue("Total de Horas Atestado:");

            HSSFCell cell12 = lastRow5.createCell(1);
            cell12.setCellStyle(lastRowStyle);
            cell12.setCellValue(txtHorasAtestado.getText());

            HSSFCell cell13 = lastRow6.createCell(0);
            cell13.setCellStyle(lastRowStyle);
            cell13.setCellValue("Total de Horas DRS:");

            HSSFCell cell14 = lastRow6.createCell(1);
            cell14.setCellStyle(lastRowStyle);
            cell14.setCellValue(txtHorasDrs.getText());

            stream.flush();
            stream.close();

            JOptionPane.showMessageDialog(null, "Exportado com sucesso!", "Sucesso!", JOptionPane.INFORMATION_MESSAGE);//ImageHelper.getImage("excel_32x32.png"));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

da linha 115 a 121 eu crio adicionar para inserir alguns dados separado.
mas quando eu clico no botão para salvar o arquivo gerado ela só cria as linha adicionais 115 á 118, da 119 ate 121 não cria.
Sera que alguém poderia me ajudar a desvendar este dilema, ficarei grato.

3 Respostas

L

Não tem a ver com o

workbook.write(stream);

na linha 156 de seu código?

G

lsouza muito obrigado você salva ou minha vida…

seria demais perguntar se você saberia colocar uma imagem com este código, para ele gerar o Excel com imagem como cabeçaria.

L

Eu já fiz isso. Depois vou dar uma olhada no projeto atual aqui se tem algo semelhante, e te falo.
To meio garrado agora na parte da tarde.
valeu!

Criado 28 de novembro de 2012
Ultima resposta 28 de nov. de 2012
Respostas 3
Participantes 2