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 controladores; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.Date; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import modelos.Fecha; import org.apache.poi.ss.usermodel.*; import org.apache.poi.hssf.usermodel.*; import org.apache.poi.xssf.usermodel.*; import reportes.Reporte; /** * * @author jeiso */ public class ExportExcel { /** * @param args the command line arguments */ Workbook wb; String RUTA_REPORTE = "MisReportes/"; public String ConsultaExportarExcel(ResultSet rs, String nombreArchivo) { String respuesta = "No se realizo con exito la exportacin."; ResultSetMetaData rsMd; try { //crea el jtable rsMd = rs.getMetaData(); int numeroColumnas = rsMd.getColumnCount(); DefaultTableModel modelo = new DefaultTableModel(); JTable tablaD = new JTable(); tablaD.setModel(modelo); for (int i = 1; i <= numeroColumnas; i++) { modelo.addColumn(rsMd.getColumnLabel(i)); } while (rs.next()) { Object[] fila = new Object[numeroColumnas]; for (int i = 0; i < numeroColumnas; i++) { fila[i] = rs.getObject(i + 1); } modelo.addRow(fila); } //crea el archivo excel File archivo = new File(RUTA_REPORTE + "Reporte " + nombreArchivo + ".xls"); archivo.createNewFile(); //aade datos al doc de excel int numFila = tablaD.getRowCount(), numColumna = tablaD.getColumnCount(); if (archivo.getName().endsWith("xls")) { wb = new HSSFWorkbook(); } else { wb = new XSSFWorkbook(); } Sheet hoja = wb.createSheet("Reporte " + nombreArchivo); for (int i = -1; i < numFila; i++) { Row fila = hoja.createRow(i + 1); for (int j = 0; j < numColumna; j++) { Cell celda = fila.createCell(j); if (i == -1) { celda.setCellValue(String.valueOf(tablaD.getColumnName(j))); } else { celda.setCellValue(String.valueOf(tablaD.getValueAt(i, j))); } wb.write(new FileOutputStream(archivo)); } } respuesta = "Exportacin exitosa."; } catch (SQLException ex) { Logger.getLogger(ExportExcel.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ExportExcel.class.getName()).log(Level.SEVERE, null, ex); } return respuesta; } // public static void main(String[] args) throws IOException { // Export ex = new Export(); // String nombreArchivo = "20160720"; // conexion con = new conexion(); // ResultSet rs = con.getConsultaSql("Select *from ciudades", con.getConexion()); // // try { // ex.ConsultaExportarExcel(rs,nombreArchivo); // } catch (SQLException ex1) { // Logger.getLogger(Export.class.getName()).log(Level.SEVERE, null, ex1); // } // } }