Como pegar um xls e subir para o banco!?

7 respostas
snowblacksoul

Galera sei que já existe esse tópico , porém decidi abrir outro pois estou com um problema na hora de importação
a tabela que preciso importar esta dessa forma


CREATE TABLE [dbo].[STOP_ATIS2](
[CD_CLIENTE] [bigint] NULL,
[CD_CONTA] [bigint] NULL,
[QTDE] [int] NULL,
[VALOR] [decimal](10, 2) NULL,
[MOTIVO] varchar NULL,
[CONTA] [int] NULL,
[CICLO] [smallint] NULL,
[TERMINAL] [bigint] NULL
) ON [PRIMARY]

O xls que estou importando está assim!?

mas está importando da seguinte forma:

o código java que estou usando para pegar as informações do xls e importar é esse?! o que estou fazendo de errado galera que ele nao pega os valores corretos apenas os strings!?

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

import connectionfactory.telefonica.com.br.ConnectionFactory;


public class Principal {

	private static int i =0;
	private static Long stringa1;
	private static Long stringa2;
	private static Long stringa3;
	private static float stringa4;
	private static String stringa5;
	private static Long stringa6;
	private static Long stringa7;
	private static Long stringa8;
	
	public static void main(String []args) throws BiffException, IOException, SQLException{
		
		Connection con = new ConnectionFactory().getConnection();
		
		Workbook workbook = Workbook.getWorkbook(new File("C:/teste/stop_atisciclo02345.xls"));
		
		Sheet sheet = workbook.getSheet(0);
		
		int linhas = sheet.getRows();
		
		for(i = 0; i < linhas; i++){
			Cell a1 = sheet.getCell(0,i);
			Cell b2 = sheet.getCell(1,i);
			Cell c3 = sheet.getCell(2,i);
			Cell d4 = sheet.getCell(3,i);
			Cell e5 = sheet.getCell(4,i);
			Cell f6 = sheet.getCell(5,i);
			Cell g7 = sheet.getCell(6,i);
			Cell h8 = sheet.getCell(7,i);
			
			
			
			
			stringa1 = (long) a1.getRow();
			stringa2 = (long) b2.getRow();
			stringa3 = (long) c3.getRow();
			stringa4 = d4.getColumn();
			stringa5 = e5.getContents();
			stringa6 = (long) f6.getRow();
			stringa7 = (long) g7.getRow();
			stringa8 = (long) h8.getRow();
			
			PreparedStatement st = con.prepareStatement("insert into STOP_ATIS2(cd_cliente,cd_conta,qtde,valor,motivo,conta,ciclo,terminal)"+"Values('"+stringa1+"','"+stringa2+"','"+stringa3+"','"+stringa4+"','"+stringa5+"','"+stringa6+"','"+stringa7+"','"+stringa8+"')");
			
			st.executeUpdate();
		}
		workbook.close();
	}
	
}

por favor peço a ajuda de vc´s gratos a quem puder me ajudar!! vale mesmo!

7 Respostas

fernandopaiva

veja isto: http://www.devmedia.com.br/post-7328-Lendo-e-escrevendo-arquivos-do-Excel-com-a-API-JXL-Parte-I.html

t+ e boa sorte.

snowblacksoul

Cara valeu mas nao me ajudou, pois estou fazendo exatamente o que ele fala
quero saber como colocar numero e outro tipo como ele diz,


Agora vamos dentro do laço for capturar os valores das células da planilha, notem o tipo de variável ?Cell? mais adiante esse tipo terá que ser tratado para string, number ou outro tipo conforme a sua necessidade, irei demostrar como efetuar essas operações mais adiante:

fernandopaiva

veja como fazer

private void btnGravaXLSClick(ActionEvent e){
     leGravaXLS();
}

public Workbook retornaWorkBook() throws IOException, BiffException{
        File arquivo = new File("/home/fernando/cod_perso.xls");
        Workbook workBook = Workbook.getWorkbook(arquivo);
        return workBook;
    }

public void leGravaXLS() throws Exception{      
 ///um SwingWorker pra deixar bonitinho o esquema  
       progresso.setIndeterminate(true);  
       jButton1.setEnabled(false);   
       jButton1.setText("Executando");
        
       SwingWorker worker = new SwingWorker() {  
            @Override  
            protected Object doInBackground() throws Exception {  
                gravaArtigo();                   
                return null;  
            }  
  
            protected void done(){  
                //barra.setValue(0);  
                inserindo.setText("Terminado");                
                progresso.setIndeterminate(false);
                progresso.setValue(0);
                jButton1.setEnabled(true);
                jButton1.setText("Executar");
                
            }  
        };  
        worker.execute();         
    }

public void gravaArtigo() throws SQLException, IOException, BiffException{ //aqui le e grava no banco
        inserindo.setText("Aguarde...");
        PreparedStatement stm = (PreparedStatement)con.prepareStatement("INSERT INTO tabela (valor1, valor2, valor3, valor4, valor5) VALUES (?,?,?,?,?)");
        Sheet sheet = retornaWorkBook().getSheet(0);
        for(int x = 0; x < sheet.getColumn(0).length ;x++){
                    //System.out.println(sheet.getCell(0,x).getContents());                    
                    stm.setString(1, sheet.getCell(0,x).getContents()); //valor1
                    stm.setString(2, sheet.getCell(2,x).getContents()); //valor2
                    stm.setString(3, sheet.getCell(3,x).getContents()); //valor3
                    stm.setString(4, "0"); //valor4
                    stm.setString(5, sheet.getCell(4,x).getContents()); //valor5
                    stm.executeUpdate();                      
        }        
    }


//classe de conexao
public class Conexao {        
        public static Connection getConnection() throws SQLException {
            try {
                Class.forName("com.mysql.jdbc.Driver");                
                return DriverManager.getConnection("jdbc:mysql://192.168.1.1/bdFernando?user=fernando&password=xxxxxxxxx");
            }catch (ClassNotFoundException e){
                throw new SQLException(e.getMessage());

            }
        }        

}

eh isso ae, simples de fazer

t+ e boa sorte

snowblacksoul

fernandopaiva blz grande!!!?

Bom até a gravação eu entendi, mas está gravando todos os dados com string!!!
eu quero gravar como numeric ou int, ou double entendeu!?

fernandopaiva

Basta converter ueh…usar Double.parseDouble etc… !

snowblacksoul

é… amigo estou tentando mas nao converte

snowblacksoul

conseguir converter porem esta dando esse erro!!!

Conectando ao Banco
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
	at java.lang.Integer.parseInt(Integer.java:470)
	at java.lang.Integer.parseInt(Integer.java:499)
	at stopatis.StopAtis.main(StopAtis.java:72)
Java Result: 1
CONSTRUÍDO COM SUCESSO (tempo total: 6 segundos)
Criado 9 de novembro de 2011
Ultima resposta 11 de nov. de 2011
Respostas 7
Participantes 2