Exportar excel para SQL

12 respostas
I

Bom dia!
Sou iniciante em java e estou tendo dificuldades em ler dados de uma planilha em excel e gravar em um banco de dados sql. O banco de dados já tem uma estrutura e já esta criado so preciso colar os dados de uma coluna em excel na coluna de uma tabela. Consegui ler o arquivo em excel mas não sei como gravar no sql. portanto gostaria de uma ajuda de vocês.
Desde já agradeço pela atenção.
Segue abaixo meu codigo:

package implantar1;

import java.io.File;
import java.io.IOException;
import jxl.Cell;
import jxl.NumberCell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import javax.swing.JOptionPane;
import java.sql.*;

public class excel {

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

        Workbook workbook = Workbook.getWorkbook(new File("teste.xls"));
        Sheet sheet = workbook.getSheet(0);
        int linhas = sheet.getRows();

        System.out.println("Iniciando a leitura da planilha XLS:");
        for (int i = 0; i < linhas; i++) {
            Cell a1 = sheet.getCell(0, i);
            Cell b1 = sheet.getCell(0, i);
            Cell c1 = sheet.getCell(0, i);
            String as1 = a1.getContents();
            //String as2 = b1.getContents();
            //String as3 = c1.getContents();
            System.out.println("Coluna 1: " + as1);
           // System.out.println("Coluna 2: " + as2);
            //System.out.println("Coluna 3: " + as3);
        }
        workbook.close();
    }
}

12 Respostas

N

Dê uma olhada neste post http://www.guj.com.br/java/66925-implementando-dao

juniorsimi

Cria um método que insere o registro no banco e passa os campos como parametros assim:

for (int i = 0; i < linhas; i++) {
	Cell a1 = sheet.getCell(0, i);
	Cell b1 = sheet.getCell(0, i);
	Cell c1 = sheet.getCell(0, i);
	
	ClasseDoBanco.insereNoBanco(a1.getContents(), b1.getContents(), c1.getContents());
}

método da classe do banco :

public insereNoBanco(String a1, String b1, String c1){

	String sql = "INSERT INTO TABELA (COLUNA1, COLUNA2, COLUNA3) VALUES (?,?,?)";

	try {
		PreparedStatement stmt = Connection.prepareStatement(sql);//Pega aqui a conexão com seu banco
		int idx = 1;
		stmt.setObject(idx++, a1, Types.VARCHAR);
		stmt.setObject(idx++, b1, Types.VARCHAR);
		stmt.setObject(idx++, c1, Types.VARCHAR);

		stmt.executeUpdate(sql)
	} catch (SQLException e) {
		
	}
}

Se for muitos campos do Excel cria um objeto e passa como parametro para o método ao invés de passar as Strings.

Espero que tenha ajudado.

ViniGodoy

Pessoal, por favor, evitem escrever usando SOMENTE MAIUSCULAS, principalmente no título dos tópicos.
Além disso, ao postar código, por favor, usem a tag code. Se ainda não sabem, leiam:

I

Junior obrigado pela dica entendi. Aqui mas também não estou conseguindo conectar no banco como ficaria a classe de conexao neste caso?
Minha classe de conectar esta o seguinte:

public class Conexao {

public static void main(String[] args) {

// string de conexão…usando Windows Authentication

String connectionUrl = jdbc:sqlserver://localhost:1433; +

“databaseName=suporte;integratedSecurity=true;;
try {
  Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
  Connection conn = DriverManager.getConnection(connectionUrl);
  System.out.println("Conexão obtida com sucesso.");
}
catch (SQLException ex) {
  System.out.println("SQLException: " + ex.getMessage());
  System.out.println("SQLState: " + ex.getSQLState());
  System.out.println("VendorError: " + ex.getErrorCode());
}
catch (Exception e) {
  System.out.println("Problemas ao tentar conectar com o banco de dados: " + e);
}

}
}

ViniGodoy

implantar:
Junior obrigado pela dica entendi. Aqui mas também não estou conseguindo conectar no banco como ficaria a classe de conexao neste caso?
Minha classe de conectar esta o seguinte:

Cadê a tag code?

I
public class Conexao {
public static void main(String[] args) {
// string de conexão...usando Windows Authentication
String connectionUrl = "jdbc:sqlserver://localhost:1433;" +
"databaseName=suporte;integratedSecurity=true;";

try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
Connection conn = DriverManager.getConnection(connectionUrl);
System.out.println("Conexão obtida com sucesso.");
}
catch (SQLException ex) {
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}
catch (Exception e) {
System.out.println("Problemas ao tentar conectar com o banco de dados: " + e);
}
}
}
juniorsimi

Qual erro retorna?

I

Problemas ao tentar conectar com o banco de dados: java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver

juniorsimi

Tenta assim:

private Connection openConnection() throws DAOException {

	String driver = "net.sourceforge.jtds.jdbc.Driver";
	String url = "jdbc:jtds:sqlserver://localhost/NOMEDOBANCO";
	String user = "usuario";
	String passwd = "senha";

	try {
		Class.forName(driver);
		conn = DriverManager.getConnection(url, user, passwd);
		conn.setAutoCommit(false);
		return conn;
	} catch (ClassNotFoundException e) {
		throw new DAOException(e);
	} catch (SQLException e) {
		throw new DAOException(e);
	}
}

E não esquece do driver jtds-1.2.2.jar :

[url]http://www.jarfinder.com/index.php/jars/search/~jtds~[/url]

I

A conexão deu certo, mas não esta inserindo nada no banco. A minha tabela onde tem que ser inserido chama produtos e coluna referencia.

Classe excel
public class excel {

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


        Workbook workbook = Workbook.getWorkbook(new File("teste.xls"));
        Sheet sheet = workbook.getSheet(0);
        int linhas = sheet.getRows();

        System.out.println("Iniciando a leitura da planilha XLS:");
        for (int i = 0; i < linhas; i++) {
            Cell a1 = sheet.getCell(0, i);
            Cell b1 = sheet.getCell(0, i);
            Cell c1 = sheet.getCell(0, i);
            String as1 = a1.getContents();
            
            System.out.println("Coluna 1: " + as1);
            Conexao.insereNoBanco(a1.getContents(), b1.getContents(), c1.getContents());
           
        }
        workbook.close();
    }
}
Classe Conexao
public class Conexao {

    static void insereNoBanco(String contents, String contents0, String contents1) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    private static class DAOException extends Exception {

        public DAOException() {
        }

        private DAOException(ClassNotFoundException e) {
            throw new UnsupportedOperationException("Not yet implemented");
        }

        private DAOException(SQLException e) {
            throw new UnsupportedOperationException("Not yet implemented");
        }
    }
    
        private Connection openConnection(Connection conn) throws  DAOException {

        String driver = "net.sourceforge.jtds.jdbc.Driver";
        String url = "jdbc:jtds:sqlserver://localhost/suporte";
        String user = "sa";
        String passwd = "123456";

        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url, user, passwd);
          //  Conexao=DriverManager.getConnection(url,user,passwd);
            conn.setAutoCommit(false);
            return conn;
        } catch (ClassNotFoundException e) {
            throw new DAOException(e);
        } catch (SQLException e) {
            throw new DAOException(e);
        }
    }
}
juniorsimi

Tenta criando essas tres classes:

public class Conexao {

	private boolean closed = false;
	
	private Connection conn;

	private Connection openConnection() throws  DAOException {  
  
       String driver = "net.sourceforge.jtds.jdbc.Driver";  
       String url = "jdbc:jtds:sqlserver://localhost/suporte";  
       String user = "sa";  
       String passwd = "123456";  
  
       try {  
           Class.forName(driver);  
           conn = DriverManager.getConnection(url, user, passwd);  
         //  Conexao=DriverManager.getConnection(url,user,passwd);  
           conn.setAutoCommit(false);  
           return conn;  
       } catch (ClassNotFoundException e) {  
           throw new DAOException(e);  
       } catch (SQLException e) {  
           throw new DAOException(e);  
       }  
   }  

}
 

public class Consulta extends Conexao {
	
	private static Consulta instance;
	
	public static synchronized Consulta getInstance() {
		if (instance == null) {
			instance = new Consulta();
		}

		return instance;
	}

	public void insereNoBanco(String contents, String contents0, String contents1) throws DAOException{
		
		try {
			Connection cn = openConnection();
			PreparedStatement ps = cn.prepareStatement("INSERT INTO produtos  (referencia) VALUES (?)");
			
			 int idx = 1;  
        	ps.setObject(idx++, contents, Types.VARCHAR);
			
			ps.executeUpdate(sql);
			 
		} catch (SQLException e) {
			throw new DAOException(e.getMessage());
		} 
				
	}
}



public class excel {  
  
    public static void main(String[] args) throws IOException, BiffException {  
  
  
       new excel().leExcel();
    }  
    
    public void leExcel(){
    
     Workbook workbook = Workbook.getWorkbook(new File("teste.xls"));  
        Sheet sheet = workbook.getSheet(0);  
        int linhas = sheet.getRows();  
  
        System.out.println("Iniciando a leitura da planilha XLS:");  
        for (int i = 0; i < linhas; i++) {  
            Cell a1 = sheet.getCell(0, i);  
            Cell b1 = sheet.getCell(0, i);  
            Cell c1 = sheet.getCell(0, i);  
            String as1 = a1.getContents();  
              
            System.out.println("Coluna 1: " + as1);  
            Conexao.getInstance().insereNoBanco(a1.getContents(), b1.getContents(), c1.getContents());  
             
        }  
        workbook.close();  
    	
    }
}
I

Deu a seguinte mensagem de erro:

Warning:  External sheet record for Biff 7 not supported

Warning:  Usage of a local non-builtin name

Iniciando a leitura da planilha XLS:

Coluna 1: 8

Exception in thread main java.lang.UnsupportedOperationException: Not yet implemented

at implantar1.Consulta.openConnection(Consulta.java:43)

at implantar1.Consulta.insereNoBanco(Consulta.java:27)

at implantar1.excel.leExcel(excel.java:36)

at implantar1.excel.main(excel.java:18)

Java Result: 1
Criado 11 de julho de 2011
Ultima resposta 12 de jul. de 2011
Respostas 12
Participantes 4