Gerar arquivo TXT com dados da tabela jTable

5 respostas
J

Boa tarde galera.

Gostaria de verificar com vocês se tem como me dar uma força.
Eu tenho uma informação de cadastro que está numa jTable como esta
na imagem abaixo.

O que eu preciso é o seguinte pegar os dados dessa jTable e exportar os dados para um arquivo txt.
Tem como me dar uma força.

obrigado…

5 Respostas

Jonathan_Medeiros

Tem sim, só dizer qual é a sua real dúvida, e junto com a dúvida posta o que tu já tem implementado de solução pro pessoal do fórum dar uma olhada e te dar uma força!

C

try {
FileWriter fileWriter = new FileWriter(new File(“Caminho do arquivo”));
BufferedWriter escreva = new BufferedWriter(fileWriter);

for (int i = 0; i < table.getRowCount(); i++) {
            Object o = ((TableModel) table.getmodel()).getrow(i);
            escreva.write(o.get"Atributo desejado");
            escreva.newLine();
        }
        
        escreva.close();
    } catch (IOException ex) {
        Logger.getLogger(ClienteWebService.class.getName()).log(Level.SEVERE, null, ex);
    }
J
try {
            for (int i = -1; i <cantFila; i++) {
                 Row fila = folha.createRow(i+1);
                 for (int j = 0;j<cantColumna; j++) {
                       Cell celda = fila.createCell(j);
                    if(i==-1) {
                        celda.setCellValue(String.valueOf(TabelaCliente.getColumnName(j)));
                    } else {
                    switch (celda.getColumnIndex()) {//inicio switch                                                    
                               case 0:
                        celda.setCellValue(String.valueOf(TabelaCliente.getValueAt(i, j)));
                            break;                                   
                            case 1:
                        celda.setCellValue(String.valueOf(TabelaCliente.getValueAt(i, j)));
                            break;                          
                           case 2:
                           celda.setCellValue(String.valueOf(TabelaCliente.getValueAt(i, j)));
                            break;                              
                            case 3:
                           celda.setCellValue(String.valueOf(TabelaCliente.getValueAt(i, j)));
                            break;                                
                            case 4:
                           celda.setCellValue(String.valueOf(TabelaCliente.getValueAt(i, j)));
                            break;                                
                    }//fim do switch                    
                     }                           
                    wb.write(new FileOutputStream(arquivo + ".TAB"));                
                }
            }
            
            JOptionPane.showMessageDialog(null, "TAB exportado com sucesso.");
        
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Por favor tente novamente"+e);
        }

Eu iniciei pensando assim em buscar os dados no final eu coloquei .TAB por o arquivo tem que fazer as separações delimitando com espaços (" ").

J

Eu tentei este modelo porém não consegui.

Jonathan_Medeiros

Este é um exemplo de solução que funciona, comentei alguns trechos do código para facilitar o entendimento, basta adaptar o código com o que você precisa!

try {
            //Path onde o arquivo será salvo
            File file = new File("C:\\Users\\UsuarioQualquer\\Desktop\\TextExportjTable.txt");

            //Caso o arquivo não exista então cria-se um novo arquivo
            if (!file.exists()) {
                file.createNewFile();
            }

            try (FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw)) {
                //Laço que percorre as colunas da jTable recuperando o nome das mesmas
                for (int i = 0; i < jTable.getColumnCount(); i++) {
                    bw.write(jTable.getModel().getColumnName(i) + " ");
                }

                //Quebra de linha no arquivo .txt
                //Windows: \r\n | Linux: \n
                bw.write("\r\n");                

                //Laço que percorre as linhas da jTable
                for (int i = 0; i < jTable.getRowCount(); i++) {

                    //Laço que percorre as colunas da jTable recuperando os valores
                    for (int j = 0; j < jTable.getColumnCount(); j++) {
                        bw.write(jTable.getModel().getValueAt(i, j) + " ");
                    }

                    //Quebra de linha no arquivo .txt
                    //Windows: \r\n | Linux: \n
                    bw.write("\r\n");
                }
            }

            System.out.println("Dados exportados com sucesso!");
        } catch (HeadlessException | IOException ex) {
            System.out.println("Erro ao exportar dados da jTable!");
        }
Criado 3 de agosto de 2018
Ultima resposta 6 de ago. de 2018
Respostas 5
Participantes 3