Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package BaseDatos; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; /** * * @author zombozo */ public class ExportarDatos extends javax.swing.JFrame { String nombreProducto, fabricante, contenedor, cantidad, precioCompra, precioVenta, fecha; ArrayList<String> filaExel = new ArrayList<>(); /** * Creates new form ExportarDatos */ public ExportarDatos() { initComponents(); agregarItems(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { exportar = new javax.swing.JButton(); compras = new javax.swing.JButton(); operacion = new javax.swing.JLabel(); jMenuBar1 = new javax.swing.JMenuBar(); operaciones = new javax.swing.JMenu(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); exportar.setText("Exportar a exel todas las ventas"); exportar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exportarActionPerformed(evt); } }); compras.setText("Exportar a exel todas las compras"); compras.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { comprasActionPerformed(evt); } }); operacion.setText("Operando:"); operaciones.setText("Operaciones"); jMenuBar1.add(operaciones); setJMenuBar(jMenuBar1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addGap(278, 278, 278) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(compras).addComponent(exportar)) .addContainerGap(397, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(operacion).addGap(271, 271, 271))); layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addGap(72, 72, 72).addComponent(exportar) .addGap(10, 10, 10).addComponent(operacion).addGap(9, 9, 9).addComponent(compras) .addContainerGap(371, Short.MAX_VALUE))); pack(); }// </editor-fold>//GEN-END:initComponents private void exportarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportarActionPerformed try { CrearExel(); } catch (Exception ex) { Logger.getLogger(ExportarDatos.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_exportarActionPerformed private void comprasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comprasActionPerformed CrearExelCompras(); }//GEN-LAST:event_comprasActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Windows".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(ExportarDatos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ExportarDatos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ExportarDatos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ExportarDatos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new ExportarDatos().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton compras; private javax.swing.JButton exportar; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JLabel operacion; private javax.swing.JMenu operaciones; // End of variables declaration//GEN-END:variables private void agregarItems() { try { ArrayList<JMenuItem> items; ItemsMenu obtenerItems = new ItemsMenu(); items = obtenerItems.items(); for (int a = 0; a < items.size(); a++) { int b = a; operaciones.add(items.get(a)); items.get(a).addActionListener(new ActionListener() { boolean estados; @Override public void actionPerformed(ActionEvent e) { // JOptionPane.showMessageDialog(rootPane, e.getActionCommand()); estados = obtenerItems.metodos(b); if (estados == true) { cerrar(); } } }); } } catch (Exception e) { } } public void cerrar() { this.dispose(); } public void CrearExel() throws IOException { FileOutputStream archivoSalida = null; try { Statement conexion = ConectarMysql.obtenerConexion().createStatement(ResultSet.CONCUR_READ_ONLY, ResultSet.TYPE_FORWARD_ONLY); HSSFWorkbook libro = new HSSFWorkbook(); HSSFSheet hoja = libro.createSheet("reporte"); String SqlVentas = "select * from ventas_realizadas"; ResultSet resultado = conexion.executeQuery(SqlVentas); HSSFRow fila = hoja.createRow((short) 0); HSSFCell celda = fila.createCell(0); celda.setCellValue("nombre del producto"); celda = fila.createCell(1); celda.setCellValue("fabricante"); celda = fila.createCell(2); celda.setCellValue("contenedor"); celda = fila.createCell(3); celda.setCellValue("cantidad"); celda = fila.createCell(4); celda.setCellValue("precio Compra"); celda = fila.createCell(5); celda.setCellValue("precio Venta"); celda = fila.createCell(6); celda.setCellValue("fecha"); if (resultado.first()) { int contador = 1; do { filaExel.clear(); fila = hoja.createRow((short) contador); obtenerDatos(resultado.getInt(2)); cantidad = resultado.getString(3); precioCompra = resultado.getString(4); precioVenta = resultado.getString(5); fecha = resultado.getString(6); filaExel.add(nombreProducto); filaExel.add(fabricante); filaExel.add(contenedor); filaExel.add(cantidad); filaExel.add(precioCompra); filaExel.add(precioVenta); filaExel.add(fecha); for (int a = 0; a < filaExel.size(); a++) { celda = fila.createCell(a); if (a == 3) { celda.setCellValue(Integer.parseInt(filaExel.get(a))); } else if (a == 4 || a == 5) { celda.setCellValue(Double.parseDouble(filaExel.get(a))); } else { celda.setCellValue(filaExel.get(a)); } } this.operacion.setText("operando : " + contador); contador++; } while (resultado.next()); } String direccionCompleta = "C:\\Users\\zombozo\\Documents\\ventas.xls"; File archivo = new File(direccionCompleta); archivoSalida = new FileOutputStream(archivo); libro.write(archivoSalida); archivoSalida.close(); conexion.close(); JOptionPane.showMessageDialog(rootPane, "Creado Correctamente, busque el archivo en la carpeta documentos"); } catch (Exception e) { JOptionPane.showMessageDialog(rootPane, "Ocurrio un error 1: " + e); } } private void obtenerDatos(int aInt) { System.out.println("" + aInt); try { Statement conexion = ConectarMysql.obtenerConexion().createStatement(ResultSet.CONCUR_READ_ONLY, ResultSet.TYPE_FORWARD_ONLY); String sql = "select * from productos where Id_producto=" + aInt; ResultSet resultado = conexion.executeQuery(sql); if (resultado.first()) { do { this.nombreProducto = resultado.getString(2); this.fabricante = resultado.getString(3); obtenerContenedor(resultado.getInt(4)); } while (resultado.next()); } conexion.close(); } catch (Exception e) { } } private void obtenerContenedor(int aInt) { try { Statement conexion = ConectarMysql.obtenerConexion().createStatement(ResultSet.CONCUR_READ_ONLY, ResultSet.TYPE_FORWARD_ONLY); String sql = "select * from contenedores where ID_contendor=" + aInt; ResultSet resultado = conexion.executeQuery(sql); if (resultado.first()) { do { contenedor = resultado.getString(2); System.out.println("contenedor " + contenedor); } while (resultado.next()); } conexion.close(); } catch (Exception e) { System.out.println(e.getMessage()); } } private void CrearExelCompras() { FileOutputStream archivoSalida = null; try { Statement conexion = ConectarMysql.obtenerConexion().createStatement(ResultSet.CONCUR_READ_ONLY, ResultSet.TYPE_FORWARD_ONLY); HSSFWorkbook libro = new HSSFWorkbook(); HSSFSheet hoja = libro.createSheet("reporte"); String SqlVentas = "select * from logCompras"; ResultSet resultado = conexion.executeQuery(SqlVentas); HSSFRow fila = hoja.createRow((short) 0); HSSFCell celda = fila.createCell(0); celda.setCellValue("nombre del producto"); celda = fila.createCell(1); celda.setCellValue("fabricante"); celda = fila.createCell(2); celda.setCellValue("contenedor"); celda = fila.createCell(3); celda.setCellValue("cantidad"); celda = fila.createCell(4); celda.setCellValue("precio Compra"); celda = fila.createCell(5); celda.setCellValue("precio Venta"); celda = fila.createCell(6); celda.setCellValue("fecha"); if (resultado.first()) { int contador = 1; do { filaExel.clear(); fila = hoja.createRow((short) contador); obtenerDatos(resultado.getInt(2)); cantidad = resultado.getString(3); precioCompra = resultado.getString(4); precioVenta = resultado.getString(5); fecha = resultado.getString(6); filaExel.add(nombreProducto); filaExel.add(fabricante); filaExel.add(contenedor); filaExel.add(cantidad); filaExel.add(precioCompra); filaExel.add(precioVenta); filaExel.add(fecha); for (int a = 0; a < filaExel.size(); a++) { celda = fila.createCell(a); if (a == 3) { celda.setCellValue(Integer.parseInt(filaExel.get(a))); } else if (a == 4 || a == 5) { celda.setCellValue(Double.parseDouble(filaExel.get(a))); } else { celda.setCellValue(filaExel.get(a)); } } this.operacion.setText("operando : " + contador); contador++; } while (resultado.next()); } String direccionCompleta = "C:\\Users\\zombozo\\Documents\\compras.xls"; File archivo = new File(direccionCompleta); archivoSalida = new FileOutputStream(archivo); libro.write(archivoSalida); archivoSalida.close(); JOptionPane.showMessageDialog(rootPane, "Creado Correctamente, busque el archivo en la carpeta documentos"); conexion.close(); } catch (Exception e) { JOptionPane.showMessageDialog(rootPane, "Ocurrio un error 1: " + e); } } }