Obtener registro seleccionado - JTable

Para esta entrada mostraremos un ejemplo de como saber que registro se ha seleccionado en una tabla con datos.

Las clases que son esenciales para este ejemplo son JTable y TableModel.  
JTable: Esta clase es utilizada para mostrar y editar tablas con 2 dimensiones.
JTable utiliza enteros para referirse tanto a las filas y las columnas, y el uso del método getValueAt (int, int) para recuperar los valores.

Exported from Notepad++
JTable tabla = new JTable(datos, columnas);

TableModel: Esta clase es una clase interfaz que contiene un conjunto de métodos que utilizará con JTable para manipulación de los registros.

Exported from Notepad++
TableModel tablaModelo = (TableModel) tabla.getModel();

Para este ejemplo crearemos dos clases:

1- DatosTabla  
2- DatosTablaMain
 
Exported from Notepad++
import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.TableModel; public class DatosTabla extends JPanel { private JTable tabla; private JScrollPane scrollPane; private JButton boton = new JButton("Aceptar"); public DatosTabla(String[] columnas, String[][] datos) { JPanel p = new JPanel(); setLayout(new GridLayout()); tabla = new JTable(datos, columnas); scrollPane = new JScrollPane(tabla); p.add(scrollPane, BorderLayout.PAGE_START); boton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { if ("Aceptar".equals(event.getActionCommand())) { verificarDatos(); } } }); p.add(boton); add(p, BorderLayout.CENTER); } public void verificarDatos() { TableModel tablaModelo; tablaModelo = (TableModel) tabla.getModel(); boolean avanzar = true; int registro = tabla.getSelectedRow(); int columna = tabla.getSelectedColumn(); if (registro == -1) { avanzar = false; } else if (columna == -1) { avanzar = false; } if (avanzar) { String strResultado = tablaModelo.getValueAt( tabla.getSelectedRow(), tabla.getSelectedColumn()).toString(); JOptionPane.showMessageDialog(null, "Dato seleccionado : " + strResultado); } else { JOptionPane.showMessageDialog(null, "No se ha seleccionado un registro"); } } }
Exported from Notepad++
import javax.swing.JFrame; public class DatosTablaMain { public static void main(String args[]) { String columnas[] = {"Código", "Nombre"}; String datos[][] = { {"1", "Ariel"}, {"2", "Solocodigo"}, {"3", "Juez"}, {"4", "Nombre4"} }; DatosTabla datosTabla = new DatosTabla(columnas, datos); JFrame form = new JFrame(); form.add(datosTabla); form.setSize(500, 600); form.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); form.setVisible(true); } }

La paciencia vence toda resistencia. La cortesía vence toda oposición. Proverbios 25:15




Resultado:
Fuentes:

Leer más...

Leer excel - POI

Apache Poi es un proyecto establecido para crear y mantener una solución para los documentos Microsoft.
Con el API del mismo nombre podemos leer y escribir archivos Excel como también Word y PowerPoint.
En este tema hablaremos de un grupo de clases que es de gran ayuda en nuestras labores como por ejemplo en la manipulación de archivos Excel:

POIFSFileSystem
HSSFWorkbook
HSSFSheet
Row
Cell

POIFSFileSystem : Esta clase es la principal del sistema POIFS encargada de la gestión en el uso de los archivos.
En esta clase podemos encontrar un constructor que recibe un parámetro de tipo InputStream.

Exported from Notepad++
String strRutaArchivo="/home/arielb/documento.xls"; FileInputStream archivoEntrada = new FileInputStream(strRutaArchivo); POIFSFileSystem poiArchivo = new POIFSFileSystem(archivoEntrada);

HSSFWorkbook: Esta es la clase utilizada para manipular el objeto resultante del archivo físico ya sea para escribir, leer y agregar nuevas hojas.

Exported from Notepad++
HSSFWorkbook libro = new HSSFWorkbook(poiArchivo );

HSSFSheet: Esta es la clase que permite manipular una hoja tomada del libro que se está manipulando, es resultante de la clase HSSFWorkbook.

Exported from Notepad++
HSSFSheet hoja = libro.getSheetAt(0);

Row: Esta clase nos permite manipular el registro de una hoja.




Cell: Esta clase nos permite manipular una celda de un registro de una hoja.
Según las especificaciones de POI, las celdas no pueden combinar formatos, es decir una celda especificada con formato numérico no puede tener en otra celda una cadena.


Agregaré un ejemplo que está compuesto por 4 fuentes:
1- ManipularLibros.java

Exported from Notepad++
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Iterator; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; public class ManipularLibros { private FileInputStream fiArchivoEntrada; private POIFSFileSystem poiArchivo; private HSSFWorkbook libro; private HSSFSheet hoja; /** * Este método se encarga de buscar el archivo en la ruta indicada. * cargando un objeto POIFSFileSystem. * @param strRutaArchivoIn : ruta completa y el nombre del archivo. * @throws FileNotFoundException * @throws IOException */ public void cargarArchivo(String strRutaArchivoIn) throws FileNotFoundException, IOException { StringBuilder builder; if (strRutaArchivoIn == null) { builder = new StringBuilder("Debe colocar una ruta válida, valor recibido["); builder.append(strRutaArchivoIn).append("]"); throw new IOException(builder.toString()); } else if (strRutaArchivoIn.trim().length() &gt; 0) { fiArchivoEntrada = new FileInputStream(strRutaArchivoIn); poiArchivo = new POIFSFileSystem(fiArchivoEntrada); } else { builder = new StringBuilder("Debe colocar una ruta válida, valor recibido["); builder.append(strRutaArchivoIn).append("]"); throw new IOException(builder.toString()); } } /** * Retorna el objeto de tipo POIFSFileSystem cargado con el método * cargarArchivo(String strRutaArchivoIn) * @return POIFSFileSystem */ public POIFSFileSystem obtenerPOIFS() { return poiArchivo; } /** * <pre>* Con este método obtenemos el libro basado en un * objeto válido de tipo POIFSFileSystem. * </pre> * @return HSSFWorkbook * @throws IOException */ public HSSFWorkbook obtenerLibro() throws IOException { if (poiArchivo != null) { libro = new HSSFWorkbook(poiArchivo); } return libro; } /** * <pre>* Con este método obtenemos la hoja indicada con un indice * que inicia desde 0 según la hoja que se desee procesar * </pre> * @param intIndiceIn * @return HSSFSheet * @throws IOException */ public HSSFSheet obtenerHoja(int intIndiceIn) throws IOException { libro = obtenerLibro(); hoja = libro.getSheetAt(intIndiceIn); return hoja; } /** * * @return */ public String toString() { StringBuilder b; b = new StringBuilder(); Iterator<row> row = hoja.rowIterator(); int i = 1, h = 1; while (row.hasNext()) { Row r = row.next(); h = 1; Iterator<cell> cel = r.cellIterator(); b.append("Registro ").append(i++).append(":\n"); while (cel.hasNext()) { b.append(" Celda ").append(h++).append(": "); Cell c = cel.next(); b.append(" ").append(c.toString()); b.append("\n"); } b.append("\n"); } return b.toString(); }

2- ProcesarDatosHoja.java
Exported from Notepad++
import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import org.apache.poi.hssf.usermodel.HSSFDateUtil; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.DateUtil; import org.apache.poi.ss.usermodel.Row; public class ProcesarDatosHoja extends ManipularLibros { /** * * @param strArchivoIn * @param intIndice * @return * @throws FileNotFoundException * @throws IOException * @throws FormatoUsuariosException */ public List cargarDatos(String strArchivoIn, int intIndice) throws FileNotFoundException, IOException, FormatoUsuariosException { Iterator<row> row = tomarRegistros(strArchivoIn, intIndice); Usuarios usuarios = null; List lista = new ArrayList(); while (row.hasNext()) { Row r = row.next(); Iterator<cell> celda = r.cellIterator(); usuarios = new Usuarios(); while (celda.hasNext()) { Cell cel = celda.next(); if (cel.getColumnIndex() == 0) { if (cel.getCellType() == 1) { usuarios.setNombre(cel.toString()); } else { establecerException(cel); } } if (cel.getColumnIndex() == 1) { if (cel.getCellType() == 1) { usuarios.setApellido(cel.toString()); } else { establecerException(cel); } } if (cel.getColumnIndex() == 2) { if (cel.getCellType() == 0) { usuarios.setEdad((int) cel.getNumericCellValue()); } else { establecerException(cel); } } if (cel.getColumnIndex() == 3) { if (cel.getCellType() == 0) { double d = HSSFDateUtil.getExcelDate(cel.getDateCellValue()); if (DateUtil.isCellDateFormatted(cel)) { Date fecha = HSSFDateUtil.getJavaDate(d); usuarios.setFecha(fecha); } else { establecerException(cel); } } else { establecerException(cel); } } } lista.add(usuarios); } return lista; } /** * * @param strArchivoIn * @param intIndice * @return * @throws FileNotFoundException * @throws IOException */ public Iterator<row> tomarRegistros(String strArchivoIn, int intIndice) throws FileNotFoundException, IOException { cargarArchivo(strArchivoIn); HSSFSheet hoja = obtenerHoja(intIndice); Iterator<row> row = hoja.rowIterator(); return row; } public void establecerException(Cell cel) throws FormatoUsuariosException { StringBuilder builder; builder = new StringBuilder(); builder.append("La columna [").append(cel.getColumnIndex()); builder.append("] tiene un valor incorrecto ["); builder.append(cel.toString()).append("]"); throw new FormatoUsuariosException(builder.toString()); } }

3- FormatoUsuariosException.java

Exported from Notepad++
public class FormatoUsuariosException extends Exception { public FormatoUsuariosException(Throwable cause) { super(cause); } public FormatoUsuariosException(String message, Throwable cause) { super(message, cause); } public FormatoUsuariosException(String message) { super(message); } public FormatoUsuariosException() { } }

4- Main.java

Exported from Notepad++
import java.io.FileNotFoundException; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; public class Main { public static void main(String arg[]) { try { ProcesarDatosHoja hoja = new ProcesarDatosHoja(); List registros = hoja.cargarDatos("/home/ariel/blog/fuentesjava/excel-POI/Libro1.xls", 0); int f, longitud=registros.size() for ( f = 0; f &lt; longitud; f++) { Usuarios u = (Usuarios) registros.get(f); System.out.println(f + 1); System.out.println(" Nombre==&gt; " + u.getNombre()); System.out.println(" Apellido==&gt; " + u.getApellido()); System.out.println(" Edad==&gt; " + u.getEdad()); if (u.getFecha() != null) { SimpleDateFormat sdf; sdf = new SimpleDateFormat("dd/MM/yyyy"); System.out.println(" Fecha==&gt; " + sdf.format(u.getFecha())); } System.out.println(); } } catch (FileNotFoundException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } catch (FormatoUsuariosException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ProcesarDatosHoja.class.getName()).log(Level.SEVERE, null, ex); } } }









Ejemplo utilizado:



Si esta entrada te fue de ayuda, no olvides hacer clic  sobre las propagandas :)

El API utilizado fue descargado del sitio de APACHE POI

Y los fuentes puedes descargarlos de :

https://github.com/arielb2/read-excel.git

El que sacrifica alabanza me honrará; Y al que ordenare su camino, Le mostraré la salvación de Dios. Salmos 50:23
Leer más...