Exportar para Excel resultado de consulta

Fala pessoal, td bem?
Bom eh o seguinte: eu desenvolvi uma interface em java q realiza consultas a um banco de dados que está no Access e o resultado é mostrado em tabela. Bom agora eu quero pegar esses resultados das consultas e exportar para o Excel para que possa ser feito planilhas. Não estou sabendo como fazer.
Por favor, alguém pode me auxiliar a resolver esse problema?
Obrigado!!

Rodrigo

Uma solução fácil seria criar um arquivo csv com extensão xls. Uma outra seria usar o Jakarta POI.

Mas como eu crio esse arquivo ou uso o Jakarta?
É que eu sou iniciante em java e estou encontrando dificuldades, mas estou estudando para superar cada uma.
Obrigado.

Rodrigo

No meu site tem exemplos http://www.furutani.eti.br/

Nao estou conseguindo acessar os exemplos.
Obrigado.

Rodrigo

Gere um txt, na primeira linha coloque os campos seprarados por “;”, nas próximas linhas coloque os valores desses campos separados por “;”. Salve o arquivo como .csv e importe no Excel, BrOffice etc. Exemplo de csv:

nome;idade;telefone
André;20;1234
Maria;30;9999

Cara, vc pode sim escrever e ler arquivos do Excel diretamente, sem ter a necessidade de ficar gerando arquivos texto e forçar uma importação no Excell, de uma olhada aqui e qualquer dúvida avisa: http://www.viamais.net/blog/?p=121.

Good luck.

Pessoal, estou encontrando dificuldades em como fazer a exportação para o excel.
Estou querendo usar o JasperReports, mas nao sei po0r onde começar. Eu já entrei no site para baixar, mas nao sei qual o plugin que o eclipse utiliza (já entrei no sitre do eclipse e nao achei).
Por favor, alguém me ajuda.
O código da aplicação está abaixo.
Obrigado.

Rodrigo

import javax.swing.SwingUtilities;
import java.awt.BorderLayout;
import javax.swing.JPanel;
import java.awt.*;
import javax.swing.*;
import java.sql.*;
import java.util.*;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import java.awt.ComponentOrientation;
import java.awt.Dimension;
import java.awt.Point;


public class sist extends JFrame {

	private JTable jTable = null;
	private Connection conn;

	public sist() throws HeadlessException {
		// TODO Auto-generated constructor stub
		super();
		initialize();
	}

	public sist(GraphicsConfiguration gc) {
		super(gc);
		// TODO Auto-generated constructor stub
		initialize();
	}

	public sist(String title) throws HeadlessException {
		super(title);
		// TODO Auto-generated constructor stub
		initialize();
	}

	public sist(String title, GraphicsConfiguration gc) {
		super(title, gc);
		// TODO Auto-generated constructor stub
		initialize();
	}
	
	private Vector getProximaLinha(ResultSet rs, ResultSetMetaData rsmd) throws SQLException{
		Vector linhaAtual = new Vector();
		for (int i=1; i<=rsmd.getColumnCount(); i++)
			linhaAtual.addElement(rs.getString(i));
		return linhaAtual;
	}
	
	private void mostraResultados(ResultSet rs) throws SQLException{
		boolean dados = rs.next();
		if(!dados){
			JOptionPane.showMessageDialog(this, "Nenhum registro encontrado");
			System.exit(0);
		}
		
		Vector colunas = new Vector();
		Vector linhas = new Vector();
		
		try{
			ResultSetMetaData rsmd = rs.getMetaData();
			
			for (int i=1; i<=rsmd.getColumnCount(); i++)
				colunas.addElement(rsmd.getColumnName(i));
			
			do{
				linhas.addElement(getProximaLinha(rs,rsmd));
			}while(rs.next());
			
			jTable = new JTable(linhas, colunas);
			jTable.setColumnSelectionAllowed(false);
			jTable.setSize(new Dimension(460, 80));
			jTable.setComponentOrientation(ComponentOrientation.UNKNOWN);
			jTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
			JScrollPane jScrollPane = new JScrollPane(jTable, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
			
			getContentPane().add(jScrollPane, java.awt.BorderLayout.CENTER);
			validate();
		}
		catch(SQLException sqlex){sqlex.printStackTrace();}
	}
	
	private void getJTable(){
		Statement statement;
		ResultSet result;
		char escolha;
		String st = "Digite:" +
				"\n1 - Todos os funcionários"+
				"\n2 - Funcionários Aposentados"+
				"\n3 - Funcionários Desligados"+
				"\n4 - Funcionários Novos"+
				"\n5 - Funcionários Ativos"+
				"\n6 - Alterações";
		String a = JOptionPane.showInputDialog(null,st);
		escolha = a.charAt(0);
		switch(escolha)
		{
		case '1':
		try{
			String query = "SELECT MATRICULAN, NOME, CARGO, LOTACAO FROM Empregados ORDER BY LOTACAO";
			statement = conn.createStatement();
			result = statement.executeQuery(query);
			mostraResultados(result);
			statement.close();
		}
		catch(SQLException sqlex){sqlex.printStackTrace();}
		break;
		case '2':
			try{
				String query = "SELECT MATRICULAN, NOME, CARGO, LOTACAO FROM Empregados WHERE LOTACAO = 'Aposentado' ORDER BY NOME";
				statement = conn.createStatement();
				result = statement.executeQuery(query);
				mostraResultados(result);
				statement.close();
			}
			catch(SQLException sqlex){sqlex.printStackTrace();}
			break;
		case '3':
			try{
				String query = "SELECT MATRICULAN, NOME, CARGO, LOTACAO FROM Empregados WHERE LOTACAO = 'Desligado' ORDER BY NOME";
				statement = conn.createStatement();
				result = statement.executeQuery(query);
				mostraResultados(result);
				statement.close();
			}
			catch(SQLException sqlex){sqlex.printStackTrace();}
			break;
		case '4':
			try{
				String query = "SELECT MATRICULAN, NOME, CARGO, LOTACAO FROM ConsultNovoFuncionario ORDER BY NOME";
				statement = conn.createStatement();
				result = statement.executeQuery(query);
				mostraResultados(result);
				statement.close();
			}
			catch(SQLException sqlex){sqlex.printStackTrace();}
			break;
		case '5':
			String carg = JOptionPane.showInputDialog("Digite o cargo desejado");
			try{
				String query = "SELECT MATRICULAN, NOME, CARGO, LOTACAO FROM Empregados WHERE CARGO='"+carg+"' AND LOTACAO NOT LIKE 'Desligado' AND LOTACAO NOT LIKE 'Aposentado' ORDER BY LOTACAO";
				statement = conn.createStatement();
				result = statement.executeQuery(query);
				mostraResultados(result);
				statement.close();
			}
			catch(SQLException sqlex){sqlex.printStackTrace();}
			break;
		case '6':
			try{
				String query = "SELECT * FROM ConsultFuncionario ORDER BY Empregados.FUNCAOC";
				statement = conn.createStatement();
				result = statement.executeQuery(query);
				mostraResultados(result);
				statement.close();
			}
			catch(SQLException sqlex){sqlex.printStackTrace();}
			break;
		default:
			String Erro = "Valor inexistente";
			JOptionPane.showMessageDialog(null,Erro,"Erro",1);
			System.exit(0);
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		sist tbet = new sist();
		tbet.setVisible(true);
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		try{
			Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
			conn = DriverManager.getConnection("jdbc:odbc:nomde_da_fonte_dados
		}
		catch(ClassNotFoundException cnfe){
			System.out.println(cnfe.getMessage());
		}
		catch(SQLException sqlex)
		{
			System.out.println(sqlex.getMessage());
		}
		getJTable();
		try{
			conn.close();
		}
		catch(SQLException sqlex){sqlex.printStackTrace();}
		this.setSize(400,230);
		this.setTitle("Consulta ao banco de dados");
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
}