Gerando Relatório em Excel sem uso de API

9 respostas
W

Amigos,
pela segunda vez venho pedir a ajuda de vcs, o problema é o seguinte: estou montando um relatorio em excel, tudo, aparentemente, funciona normalmente, ele gera os dados todos certinhos, entretanto os campo numericos estão como TEXTO, ou seja, se eu fizer um =soma(xx : xx) não me retornar a soma das celulas, como faço pra ele gerar o numero inteiro? abaixo está a parte do código

rs = stam.executeQuery(st);

            WritableSheet sheet = workbook.createSheet("teste", 0);

            Label label = new Label(0, 0, "teste");
            sheet.addCell(label);

            label = new Label(0, 1, "Período de " + diaDataIni+"/"+mesDataIni+"/"+anoDataIni+ " a " + diaDataFin+"/"+mesDataFin+"/"+anoDataFin+ "");
            sheet.addCell(label);

            label = new Label(0, 3, "Idade 0 a 20");
            sheet.addCell(label);            

            label = new Label(1, 3, "Idade 21 a 25");
            sheet.addCell(label);

            label = new Label(2, 3, "Idade 26 a 30");
            sheet.addCell(label);

            label = new Label(3, 3, "Idade 31 a 35");
            sheet.addCell(label);

            label = new Label(4, 3, "Idade 36 a 40");
            sheet.addCell(label);

            label = new Label(5, 3, "Idade 41 a 45");
            sheet.addCell(label);

            label = new Label(6, 3, "Idade 46 a 50");
            sheet.addCell(label);

            label = new Label(7, 3, "Idade 51 a 55");
            sheet.addCell(label);

            label = new Label(8, 3, "Idade 56 a 60");
            sheet.addCell(label);

            label = new Label(9, 3, "Idade 61 a 70");
            sheet.addCell(label);

            label = new Label(10, 3, "Idade maior 71");
            sheet.addCell(label);

            
            while (rs.next()) {
            
            String linha = String.format(rs.getString("Idade_00_a_20"));
            label = new Label (0, 5,linha);                                    
            sheet.addCell(label);
            
            linha = String.valueOf(rs.getString("Idade_21_a_25"));
            label = new Label(1, 5, linha);
            sheet.addCell(label);
            
            linha = String.format(rs.getString("Idade_26_a_30"));
            label = new Label(2, 5, linha);
            sheet.addCell(label);
            
            linha = String.format(rs.getString("Idade_31_a_35"));
            label = new Label(3, 5, linha);
            sheet.addCell(label);
            
            linha = String.format(rs.getString("Idade_36_a_40"));
            label = new Label(4, 5, linha);
            sheet.addCell(label);
            
            linha = String.format(rs.getString("Idade_41_a_45"));
            label = new Label(5, 5, linha);
            sheet.addCell(label);
            
            linha = String.format(rs.getString("Idade_46_a_50"));
            label = new Label(6, 5, linha);
            sheet.addCell(label);
            
            linha = String.format(rs.getString("Idade_51_a_55"));
            label = new Label(7, 5, linha);
            sheet.addCell(label);

            linha = String.format(rs.getString("Idade_56_a_60"));
            label = new Label(8, 5, linha);
            sheet.addCell(label);

            linha =String.format(rs.getString("Idade_61_a_70"));
            label = new Label(9, 5, linha);
            sheet.addCell(label);

            linha = String.format(rs.getString("Idade_Acima__71"));
            label = new Label(10, 5, linha);
            sheet.addCell(label);
                
            }
            workbook.write();
            workbook.close();
        } catch (Exception e) {
            System.err.println("ERRO SQL Server " + e);
        }
        JOptionPane.showMessageDialog(null, "Arquivo Gerado com Sucesso.");
        return rs;
    }

}

Eu acho que e o LABEL que aceita somente String, porém não sei o que usar para substituí-lo.

se puderem me ajudar agradeço.

Willian Baldez

9 Respostas

renato.marquez

Você está usando a biblioteca JXL? Se sim, acho que a minha dica funciona :wink:

Dentro do laço while, onde você começa a usar a instância de ResultSet para resgatar as idades, tente usar, invés do jxl.write.Label, o jxl.write.Number. Assim:

jxl.write.Number number = new jxl.write.Number(0, 5,rs.getInt("Idade_00_a_20")); sheet.addCell(number);

Aplica esse raciocínio às demais células numéricas do seu código.

W

Vlw Renato funfou… :smiley:

renato.marquez

De nada… Precisar, estamos aí :thumbup:

V

Fala ae cara,

Por acaso vc sabe de alguma API que eu passaria somente o resultSet (ou um list) e ele gera o arquivo excel…

Att.

leoramos

Cara, baseado em templates, podes usar o Apache POI. Mas na realidade, até o JasperReports pode gerar isso pra ti.
Abraço!

leoramos

Post errado, não era nesse tópico.

V

Opa, valeu mesmo pela força… vou avaliar aqui e vou postando os resultados…

renato.marquez
vitorfarias:
Fala ae cara,

Por acaso vc sabe de alguma API que eu passaria somente o resultSet (ou um list) e ele gera o arquivo excel...

Att.

Cara, sinceramente não conheço nenhuma API ou FrameWork ou qualquer coisa do gênero que faça isso, mas é simples fazer isso que você quer. Eu tenho um código de uma classe que construi aqui, por exemplo, que faz isso. Segue:

import java.io.IOException;
import java.io.OutputStream;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.table.AbstractTableModel;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;

/**
 *
 * @author Renato
 */
public final class ExcelUtil {

    public static void export(AbstractTableModel tableModel, OutputStream out, String sheetName) throws IOException {
        try {
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet(sheetName);

            HSSFRow row = sheet.createRow(0);
            for (int i = 0; i < tableModel.getColumnCount(); i++) {
                HSSFCell cell = row.createCell(i);
                cell.setCellValue(tableModel.getColumnName(i));
                HSSFCellStyle cellStyle = workbook.createCellStyle();
                cellStyle.setFillForegroundColor(HSSFColor.LIGHT_CORNFLOWER_BLUE.index);
                cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
                cell.setCellStyle(cellStyle);
            }

            for (int i = 0; i < tableModel.getRowCount(); i++) {
                row = sheet.createRow(i + 1);
                for (int j = 0; j < tableModel.getColumnCount(); j++) {
                    Object value = tableModel.getValueAt(i, j);
                    HSSFCell cell = row.createCell(j);
                    if (value.getClass().equals(Number.class)) {
                        cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
                        cell.setCellValue((Double) value);
                    } else if (value.getClass().equals(String.class)) {
                        cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                        cell.setCellValue((String) value);
                    }
                }
            }

            workbook.write(out);
        } finally {
            out.flush();
            out.close();
        }
    }

    //Esse método eu não testei ainda
    public static void export(ResultSet resultSet, OutputStream out, String sheetName) throws IOException, SQLException {
        try {
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet(sheetName);

            HSSFRow row = sheet.createRow(0);
            for (int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++) {
                HSSFCell cell = row.createCell(i);
                cell.setCellValue(resultSet.getMetaData().getColumnName(i));
                HSSFCellStyle cellStyle = workbook.createCellStyle();
                cellStyle.setFillForegroundColor(HSSFColor.LIGHT_CORNFLOWER_BLUE.index);
                cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
                cell.setCellStyle(cellStyle);
            }

            while (resultSet.next()) {
                row = sheet.createRow(resultSet.getRow());
                for (int j = 1; j <= resultSet.getMetaData().getColumnCount(); j++) {
                    Object value = resultSet.getObject(resultSet.getMetaData().getColumnName(j));
                    HSSFCell cell = row.createCell(j - 1);
                    if (value.getClass().equals(Number.class)) {
                        cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
                        cell.setCellValue((Double) value);
                    } else if (value.getClass().equals(String.class)) {
                        cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                        cell.setCellValue((String) value);
                    }
                }
            }

            workbook.write(out);
        } finally {
            out.flush();
            out.close();
        }
    }

}

Com o auxílio do jogo de IFs (que aliás, você pode jogar em um método a parte só para realizar essas comparações), você pode determinar formatos diferentes para a sua célula. No caso, eu só tratei tipos Number e String, mas aí acho que já dá para tirar uma ideia e fazer para o restante dos tipos conforme sua necessidade, certo?

Ah, você tem que incluir a lib Apache POI para manipular arquivos do Excel utilizando a minha classe acima. Fique a vontade para usar e modificar a classe. :wink:

Abraços!

V

Cara simplesmente incrivél… vou precisar alterar sua classe para imprimir outras abas e acertar a formatação…
e posto aqui para ajudar outros amigos…

Muito obrigado mesmo, poupou bastante tempo de pesquisa…

Criado 12 de março de 2011
Ultima resposta 4 de abr. de 2011
Respostas 9
Participantes 4