Copy content from a Jtable to a File.txt

-1

I am entering data at a jTable and through a jButton , I want to copy the information from the rows of jTable into a text file.

public NuevaVenta() {
    initComponents();

    Date fecha = new Date(); //fecha y hora actual
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); //formatear la fecha en una cadena
    FechaAc.setText(sdf.format(fecha)); //setear la representacion en cadena de la fech

       //Manejo de archivos
    File ventas = new File("Ventas.txt"); //vinculo el archivo a mi variable
    if(!ventas.exists()){//si el archivo no existe lo creo
        try {
            ventas.createNewFile();// creo el archivo
        } catch (IOException ex) {
            Logger.getLogger(PastasFrescaElBuenGusto.class.getName()).log(Level.SEVERE, null, ex);
        }
   }
   /*
   FileReader fr = new FileReader(ventas);// variable para leer el archivo    
   BufferedReader br = new BufferedReader(fr);//variable para almacenar el archivo
   */

    //tabVentas
    String titulos4 [] = {"Descripcion","Cant" };// creando la tabla a gusto
    String filas4 [][] = {};

    mt4 = new DefaultTableModel(filas4, titulos4);

    TableColumnModel colVentas = TabVentas.getColumnModel(); //para poder modificar los anchos de las columnas

    TabVentas.setModel(mt4);// para poder mostrar la tabla
    //para que te tome la modificacion del tamanio tenes que hacerlo despues de mostrar la tabla
    colVentas.getColumn(1).setPreferredWidth(55);
    colVentas.getColumn(0).setPreferredWidth(300);
}

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    int confirmado = JOptionPane.showConfirmDialog(this,"Esta seguro de la operacion?","Seleccione una opcion" , JOptionPane.YES_NO_OPTION);
    if (JOptionPane.OK_OPTION == confirmado) {
        //Codigo para pasar jTable a txt
    }
}
    
asked by Jorge Gonzalez 07.03.2016 в 23:55
source

1 answer

2

I share a method, which saves the content of JTable in a file .txt :

   private void guardaTabla(){
        try {

            String sucursalesCSVFile = "src/archivos/DatosTabla.txt";
            BufferedWriter bfw = new BufferedWriter(new FileWriter(sucursalesCSVFile ));

            for (int i = 0 ; i < table.getRowCount(); i++) //realiza un barrido por filas.
            {
                for(int j = 0 ; j < table.getColumnCount();j++) //realiza un barrido por columnas.
                {
                    bfw.write((String)(table.getValueAt(i,j)));
                    if (j < table.getColumnCount() -1) { //agrega separador "," si no es el ultimo elemento de la fila.
                        bfw.write(",");
                    }
                }
                bfw.newLine(); //inserta nueva linea.
            }

            bfw.close(); //cierra archivo!
            System.out.println("El archivo fue salvado correctamente!");
        } catch (IOException e) {
            System.out.println("ERROR: Ocurrio un problema al salvar el archivo!" + e.getMessage());
        }
    }

Add a listener to your button to call the previous method:

   btnSalvar.addActionListener(new ActionListener() {
            public void actionPerformed (final ActionEvent d) {

                guardaTabla();

            }});
    
answered by 08.03.2016 / 00:28
source