1. java
  2. android
  3. c#
  4. .net
  5. javascript
  6. php
  7. jquery
  8. html
  9. sql

[RESOLVIDO]Erro ao exportar arquivo .XLS no NetBeans

Boa tarde,

Estou tentando fazer uma exportação de arquivo .XLS a partir de uma jTable, quando clico em exportar da o seguinte erro

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at br.com.controller.EmailMarketingController.exportExcelFile(EmailMarketingController.java:109)
    at br.com.view.ConsutaEmail.lambda$jButtonExportarActionPerformed$0(ConsutaEmail.java:336)
    at br.com.view.ConsutaEmail$$Lambda$26/21191151.actionPerformed(Unknown Source)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2346)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6525)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
    at java.awt.Component.processEvent(Component.java:6290)
    at java.awt.Container.processEvent(Container.java:2234)
    at java.awt.Component.dispatchEventImpl(Component.java:4881)
    at java.awt.Container.dispatchEventImpl(Container.java:2292)
    at java.awt.Component.dispatchEvent(Component.java:4703)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4898)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4533)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4462)
    at java.awt.Container.dispatchEventImpl(Container.java:2278)
    at java.awt.Window.dispatchEventImpl(Window.java:2750)
    at java.awt.Component.dispatchEvent(Component.java:4703)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:86)
    at java.awt.EventQueue$4.run(EventQueue.java:731)
    at java.awt.EventQueue$4.run(EventQueue.java:729)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

e então a planilha é gerada sem nenhum dado;

segue o código da classe onde fica a jTable e o código que vai gerar a j table de visualização para exportar:

/*
 * 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 br.com.view;

import br.com.bean.EmailMarketing;
import br.com.model.EmailMarketingModel;
import br.com.controller.EmailMarketingController;
import static java.awt.Frame.MAXIMIZED_BOTH;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.io.File;
import java.io.IOException;
import javax.swing.JTable;



/**
 *
 * @author h.schmidt
 */
public class ConsutaEmail extends javax.swing.JFrame {

    private ArrayList<EmailMarketing> lista;
    DefaultTableModel modelo = new DefaultTableModel();

    /**
     * Creates new form ConsutaEmail
     */
    public final void CentralizarFrame() {
        int x, y;
        Rectangle scr = this.getGraphicsConfiguration().getBounds();
        Rectangle form = this.getBounds();

        x = (int) (scr.getWidth() - form.getWidth()) / 2;
        y = (int) (scr.getHeight() - form.getHeight()) / 2;
        this.setLocation(x, y);
        this.setExtendedState(MAXIMIZED_BOTH);
    }

    public ConsutaEmail() {
        initComponents();
        this.CentralizarFrame();

    }

    /**
     * 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">                          
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTableConsultaEMail = new javax.swing.JTable();
        jButtonInserir = new javax.swing.JButton();
        jButtonSair = new javax.swing.JButton();
        jButtonExportar = new javax.swing.JButton();
        jButtonRemover = new javax.swing.JButton();
        jButtonEmailDESC = new javax.swing.JButton();
        jButtonEmailAsc = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jTableConsultaEMail.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        jTableConsultaEMail.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null}
            },
            new String [] {
                "ID", "EMAIL ", "LISTA GEEKLE", "ORIGEM CENTRAL", "SITUAÇÃO", "DIVISÃO", "OBSERVAÇÕES", "Contato WEB", "F/J", "NAC/INT", "PROVIDENCIA", "ATIVIDADE", "CIDADE", "UF", "BAIRRO", "REGIÃO"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTableConsultaEMail.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(jTableConsultaEMail);

        jButtonInserir.setText("Inserir");
        jButtonInserir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonInserirActionPerformed(evt);
            }
        });

        jButtonSair.setText("Sair");
        jButtonSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSairActionPerformed(evt);
            }
        });

        jButtonExportar.setText("Expotar");
        jButtonExportar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonExportarActionPerformed(evt);
            }
        });

        jButtonConsultar.setText("Consultar");
        jButtonConsultar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonConsultarActionPerformed(evt);
            }
        });

        jButtonRemover.setText("Remover");
        jButtonRemover.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonRemoverActionPerformed(evt);
            }
        });

        jButtonEmailDESC.setText("DESC");
        jButtonEmailDESC.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonEmailDESCActionPerformed(evt);
            }
        });

        jButtonEmailAsc.setText("ASC");
        jButtonEmailAsc.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonEmailAscActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 1259, Short.MAX_VALUE)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButtonEmailAsc, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonInserir, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(10, 10, 10)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jButtonRemover, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButtonEmailDESC, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButtonConsultar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButtonExportar, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButtonSair, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonInserir)
                    .addComponent(jButtonConsultar)
                    .addComponent(jButtonSair)
                    .addComponent(jButtonRemover)
                    .addComponent(jButtonExportar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonEmailAsc)
                    .addComponent(jButtonEmailDESC))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 624, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(71, 71, 71))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 696, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>                        

    private void jButtonConsultarActionPerformed(java.awt.event.ActionEvent evt) {                                                 

        try {

            modelo.setColumnIdentifiers(new String[]{"ID", "EMAIL", "LISTA GEEKLE",
                "ORIGEM CENTRAL", "SITUAÇÃO", "OBSERVAÇÃO", "Contato WEB", "F/J", "NAC/INT",
                "PROVIDENCIA", "ATIVIDADE", "CIDADE", "UF", "BAIRRO", "REGIÃO"});
            EmailMarketingModel emailMarketingModel = EmailMarketingModel.obterInstancia();
            this.lista = emailMarketingModel.listarTodos();
            for (int i = 0; i < lista.size(); i++) {
                modelo.addRow(new Object[]{
                    this.lista.get(i).getId(),
                    this.lista.get(i).getE_Mail(), this.lista.get(i).getListaGeekle(),
                    this.lista.get(i).getOrigemCentral(), this.lista.get(i).getSituacao(),
                    this.lista.get(i).getObservacoes(), this.lista.get(i).getContatoWeb(),
                    this.lista.get(i).getF_j(), this.lista.get(i).getNacInt(),
                    this.lista.get(i).getProvidencia(), this.lista.get(i).getAtividade(),
                    this.lista.get(i).getCidade(), this.lista.get(i).getUF(),
                    this.lista.get(i).getBairro(), this.lista.get(i).getRegiao()});
            }
            jTableConsultaEMail.setModel(modelo);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
    }                                                

    private void jButtonExportarActionPerformed(java.awt.event.ActionEvent evt) {                                                

        JFrame frame = new JFrame("exportação de excel");
        EmailMarketingController emailMarketingController = new EmailMarketingController();
        final JTable table = new JTable(modelo);
        JScrollPane jsp = new JScrollPane(table);
        JButton export = new JButton("Exportar");
        export.addActionListener((ActionEvent e) -> {
            try {
                emailMarketingController.exportExcelFile(table,
                        new File("C:/Users/h.schmidt/Documents/testes planilhas/ItemDeExportação.xls"));

            } catch (IOException ex) {
                ex.getMessage();

            }
        });
        frame.getContentPane().add("Center", jsp);
        frame.getContentPane().add("South", export);
        frame.pack();

        frame.setVisible(true);

        //JOptionPane.showMessageDialog(null, "Função indisponivel no momento...");


    }                                               

    private void jButtonSairActionPerformed(java.awt.event.ActionEvent evt) {                                            
        dispose();
    }                                           

    private void jButtonInserirActionPerformed(java.awt.event.ActionEvent evt) {                                               
        // TODO add your handling code here:
    }                                              

    private void jButtonEmailAscActionPerformed(java.awt.event.ActionEvent evt) {                                                
        try {
            DefaultTableModel modelo = new DefaultTableModel();
            modelo.setColumnIdentifiers(new String[]{"ID", "EMAIL", "LISTA GEEKLE",
                "ORIGEM CENTRAL", "SITUAÇÃO", "OBSERVAÇÃO", "Contato WEB", "F/J", "NAC/INT",
                "PROVIDENCIA", "ATIVIDADE", "CIDADE", "UF", "BAIRRO", "REGIÃO"});
            EmailMarketingModel emailMarketingModel = EmailMarketingModel.obterInstancia();
            this.lista = emailMarketingModel.listarTodosEmailASC();
            for (int i = 0; i < lista.size(); i++) {
                modelo.addRow(new Object[]{
                    this.lista.get(i).getId(),
                    this.lista.get(i).getE_Mail(), this.lista.get(i).getListaGeekle(),
                    this.lista.get(i).getOrigemCentral(), this.lista.get(i).getSituacao(),
                    this.lista.get(i).getObservacoes(), this.lista.get(i).getContatoWeb(),
                    this.lista.get(i).getF_j(), this.lista.get(i).getNacInt(),
                    this.lista.get(i).getProvidencia(), this.lista.get(i).getAtividade(),
                    this.lista.get(i).getCidade(), this.lista.get(i).getUF(),
                    this.lista.get(i).getBairro(), this.lista.get(i).getRegiao()});
            }
            jTableConsultaEMail.setModel(modelo);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
    }                                               

    private void jButtonEmailDESCActionPerformed(java.awt.event.ActionEvent evt) {                                                 
        try {
            DefaultTableModel modelo = new DefaultTableModel();
            modelo.setColumnIdentifiers(new String[]{"ID", "EMAIL", "LISTA GEEKLE",
                "ORIGEM CENTRAL", "SITUAÇÃO", "OBSERVAÇÃO", "Contato WEB", "F/J", "NAC/INT",
                "PROVIDENCIA", "ATIVIDADE", "CIDADE", "UF", "BAIRRO", "REGIÃO"});
            EmailMarketingModel emailMarketingModel = EmailMarketingModel.obterInstancia();
            this.lista = emailMarketingModel.listarTodosEmailDESC();
            for (int i = 0; i < lista.size(); i++) {
                modelo.addRow(new Object[]{
                    this.lista.get(i).getId(),
                    this.lista.get(i).getE_Mail(), this.lista.get(i).getListaGeekle(),
                    this.lista.get(i).getOrigemCentral(), this.lista.get(i).getSituacao(),
                    this.lista.get(i).getObservacoes(), this.lista.get(i).getContatoWeb(),
                    this.lista.get(i).getF_j(), this.lista.get(i).getNacInt(),
                    this.lista.get(i).getProvidencia(), this.lista.get(i).getAtividade(),
                    this.lista.get(i).getCidade(), this.lista.get(i).getUF(),
                    this.lista.get(i).getBairro(), this.lista.get(i).getRegiao()});
            }
            jTableConsultaEMail.setModel(modelo);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
    }                                                

    private void jButtonRemoverActionPerformed(java.awt.event.ActionEvent evt) {                                               


    }                                              

    /**
     * @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 ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ConsutaEmail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ConsutaEmail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ConsutaEmail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ConsutaEmail.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 ConsutaEmail().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    public static final javax.swing.JButton jButtonConsultar = new javax.swing.JButton();
    private javax.swing.JButton jButtonEmailAsc;
    private javax.swing.JButton jButtonEmailDESC;
    public static javax.swing.JButton jButtonExportar;
    private javax.swing.JButton jButtonInserir;
    private javax.swing.JButton jButtonRemover;
    private javax.swing.JButton jButtonSair;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    public static javax.swing.JTable jTableConsultaEMail;
    // End of variables declaration                   
}

Segue a classe que esta fazendo o preenchimento da tabela com os dados do banco:

/*
 * 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 br.com.model;

import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JOptionPane;
import br.com.util.Conexao;
import br.com.bean.EmailMarketing;
import br.com.util.Progress;
import java.util.ArrayList;


/**
 *
 * @author Schmidt
 */
public class EmailMarketingModel {

    private ResultSet res;
    private final Conexao conexao;

    private StringBuilder query;
    private final ArrayList<EmailMarketing> lista;
    private static EmailMarketingModel InstanciaRep;
    private Object p;

    public EmailMarketingModel() {
        conexao = new Conexao();
        this.lista = new ArrayList<>();
    }

    public void inserirEmailMarketing(EmailMarketing mail) {
        try {
            query = new StringBuilder();
            query.append("insert into cliente (id, email, listageekle, origemcentral, "
                    + "situacao, divisoes, observacoes, contatoweb, f/j, nac/int, providencia, "
                    + "atividade, cidade, uf, bairro, regiao)");
            query.append("values('");
            query.append(mail.getId());
            query.append("','");
            query.append(mail.getE_Mail());
            query.append("','");
            query.append(mail.getListaGeekle());
            query.append("','");
            query.append(mail.getOrigemCentral());
            query.append("','");
            query.append(mail.getSituacao());
            query.append("','");
            query.append(mail.getDivisao());
            query.append("','");
            query.append(mail.getObservacoes());
            query.append("','");
            query.append(mail.getContatoWeb());
            query.append("','");
            query.append(mail.getF_j());
            query.append("','");
            query.append(mail.getNacInt());
            query.append("','");
            query.append(mail.getProvidencia());
            query.append("','");
            query.append(mail.getAtividade());
            query.append("','");
            query.append(mail.getCidade());
            query.append("','");
            query.append(mail.getUF());
            query.append("','");
            query.append(mail.getBairro());
            query.append("','");
            query.append(mail.getRegiao());
            query.append("')");

            conexao.openConnection();
            conexao.executeUpdate(query);

            JOptionPane.showMessageDialog(null,
                    "Email inserido com sucesso!");
        } catch (Exception erro) {
            JOptionPane.showMessageDialog(null,
                    "Erro a tentar Gravar o registro..." + erro);
        } finally {
            conexao.closeConnection();
        }
    }

    public void deletarEmail(EmailMarketing mail) {

        try {

            String info = "Deseja Deletar '" + mail.getE_Mail() + "', Cuja ID = '"
                    + mail.getId() + "' ?";
            int opcao_escolhida = JOptionPane.showConfirmDialog(null, info,
                    "Exclusao ", JOptionPane.YES_NO_OPTION);
            if (opcao_escolhida == JOptionPane.YES_OPTION) {
                query = new StringBuilder();
                query.append("delete from arquivo_mail2 where email = '");
                query.append(mail.getE_Mail());
                query.append("' and id = '");
                query.append(mail.getId());
                query.append("';");

                conexao.openConnection();
                conexao.executeUpdate(query);

                //if (conseguiu_excluir == 1) {
                //valoresDefault();
                JOptionPane.showMessageDialog(null,
                        "Exclusão realizada com sucesso");
                //}
            }
        } catch (Exception erro) {
            JOptionPane.showMessageDialog(null,
                    "Erro a tentar deletar o registro..." + erro);
        } finally {
            conexao.closeConnection();
        }
    }

    public ArrayList<EmailMarketing> listarTodos() {

        @SuppressWarnings("Convert2Diamond")
        ArrayList<EmailMarketing> retorno = new ArrayList<EmailMarketing>();
        query = new StringBuilder();
        query.append("SELECT * FROM arquivo_mail2  ");
        final Progress p = new Progress();  
        p.setVisible(true);
        try {

            conexao.openConnection();
            res = conexao.executeQuery(query);


            while (res.next()) {
                EmailMarketing emailMarketing = new EmailMarketing();
                emailMarketing.setId(res.getInt("id"));
                emailMarketing.setE_Mail(res.getString("email"));
                emailMarketing.setListaGeekle(res.getString("listageekle"));
                emailMarketing.setOrigemCentral(res.getString("origemcentral"));
                emailMarketing.setSituacao(res.getString("situacao"));
                emailMarketing.setDivisao(res.getString("divisoes"));
                emailMarketing.setObservacoes(res.getString("observacoes"));
                emailMarketing.setContatoWeb(res.getString("contatoweb"));
                emailMarketing.setF_j(res.getString("f/j"));
                emailMarketing.setNacInt(res.getString("nac/int"));
                emailMarketing.setProvidencia(res.getString("providencia"));
                emailMarketing.setAtividade(res.getString("atividade"));
                emailMarketing.setCidade(res.getString("cidade"));
                emailMarketing.setUF(res.getString("uf"));
                emailMarketing.setBairro(res.getString("bairro"));
                emailMarketing.setRegiao(res.getString("regiao"));
                retorno.add(emailMarketing);

            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(null, e.getMessage());
        }

        conexao.closeConnection();
        return retorno;

    }

    public ArrayList<EmailMarketing> listarTodosEmailASC() {

        @SuppressWarnings("Convert2Diamond")
        ArrayList<EmailMarketing> retorno = new ArrayList<EmailMarketing>();
        query = new StringBuilder();
        query.append("SELECT * FROM arquivo_mail2 order by email asc ");
        try {
            conexao.openConnection();
            res = conexao.executeQuery(query);

            while (res.next()) {
                EmailMarketing emailMarketing = new EmailMarketing();
                emailMarketing.setId(res.getInt("id"));
                emailMarketing.setE_Mail(res.getString("email"));
                emailMarketing.setListaGeekle(res.getString("listageekle"));
                emailMarketing.setOrigemCentral(res.getString("origemcentral"));
                emailMarketing.setSituacao(res.getString("situacao"));
                emailMarketing.setDivisao(res.getString("divisoes"));
                emailMarketing.setObservacoes(res.getString("observacoes"));
                emailMarketing.setContatoWeb(res.getString("contatoweb"));
                emailMarketing.setF_j(res.getString("f/j"));
                emailMarketing.setNacInt(res.getString("nac/int"));
                emailMarketing.setProvidencia(res.getString("providencia"));
                emailMarketing.setAtividade(res.getString("atividade"));
                emailMarketing.setCidade(res.getString("cidade"));
                emailMarketing.setUF(res.getString("uf"));
                emailMarketing.setBairro(res.getString("bairro"));
                emailMarketing.setRegiao(res.getString("regiao"));
                retorno.add(emailMarketing);
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(null, e.getMessage());
        }
        conexao.closeConnection();
        return retorno;

    }

    public ArrayList<EmailMarketing> listarTodosEmailDESC() {

        @SuppressWarnings("Convert2Diamond")
        ArrayList<EmailMarketing> retorno = new ArrayList<EmailMarketing>();
        query = new StringBuilder();
        query.append("SELECT * FROM arquivo_mail2 order by email desc ");
        try {
            conexao.openConnection();
            res = conexao.executeQuery(query);

            while (res.next()) {
                EmailMarketing emailMarketing = new EmailMarketing();
                emailMarketing.setId(res.getInt("id"));
                emailMarketing.setE_Mail(res.getString("email"));
                emailMarketing.setListaGeekle(res.getString("listageekle"));
                emailMarketing.setOrigemCentral(res.getString("origemcentral"));
                emailMarketing.setSituacao(res.getString("situacao"));
                emailMarketing.setDivisao(res.getString("divisoes"));
                emailMarketing.setObservacoes(res.getString("observacoes"));
                emailMarketing.setContatoWeb(res.getString("contatoweb"));
                emailMarketing.setF_j(res.getString("f/j"));
                emailMarketing.setNacInt(res.getString("nac/int"));
                emailMarketing.setProvidencia(res.getString("providencia"));
                emailMarketing.setAtividade(res.getString("atividade"));
                emailMarketing.setCidade(res.getString("cidade"));
                emailMarketing.setUF(res.getString("uf"));
                emailMarketing.setBairro(res.getString("bairro"));
                emailMarketing.setRegiao(res.getString("regiao"));
                retorno.add(emailMarketing);
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(null, e.getMessage());
        }
        conexao.closeConnection();
        return retorno;

    }

    public int VerificaExistencia(EmailMarketing emailMarketing) {
        int retorno = -1;
        for (int i = 0; i < this.lista.size(); i++) {
            if (emailMarketing.getE_Mail().trim().equals(this.lista.get(i).getE_Mail().trim())) {
                retorno = i;
                break;
            }
        }
        return retorno;
    }

    public static EmailMarketingModel obterInstancia() {
        if (InstanciaRep == null) {
            InstanciaRep = new EmailMarketingModel();
        }
        return InstanciaRep;
    }

    public void AtualizaEmailMarketing(EmailMarketing mail) {
query.append("insert into cliente (id, email, listageekle, origemcentral, "
                    + "situacao, divisoes, observacoes, contatoweb, f/j, nac/int, providencia, "
                    + "atividade, cidade, uf, bairro, regiao)");
        try {
            query = new StringBuilder();

            query.append("UPDATE arquivo_mail2 SET email = '");
            query.append(mail.getE_Mail());
            query.append("',listageekle ='");
            query.append(mail.getListaGeekle());
            query.append("', origemcentral ='");
            query.append(mail.getOrigemCentral());
            query.append("', situacao ='");
            query.append(mail.getSituacao());
            query.append("', divisoes ='");
            query.append(mail.getDivisao());
            query.append("',observacoes ='");
            query.append(mail.getObservacoes());
            query.append("',contatoweb ='");
            query.append(mail.getContatoWeb());
            query.append("', f/j ='");
            query.append(mail.getF_j());
            query.append("', nac/int ='");
            query.append(mail.getNacInt());
            query.append("', providencia ='");
            query.append(mail.getProvidencia());
            query.append("', atividade ='");
            query.append(mail.getAtividade());
            query.append("', cidade ='");
            query.append(mail.getCidade());
            query.append("', uf ='");
            query.append(mail.getUF());
            query.append("', bairro ='");
            query.append(mail.getBairro());
            query.append("', regiao ='");
            query.append(mail.getRegiao());
            query.append("'");
            query.append(" WHERE id = '");
            query.append(mail.getId());
            query.append("'");

            conexao.openConnection();
            conexao.executeUpdate(query);
            JOptionPane.showMessageDialog(null,
                    "Alteracao realizada com sucesso!");

        } catch (Exception erro) {
            JOptionPane.showMessageDialog(null,
                    "Erro a tentar Alterar o registro..." + erro);
        } finally {
            conexao.closeConnection();
        }
    }

}

e por fim, segue a classe que esta exportando o arquivo .XLS:

/*
 * 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 br.com.controller;

/**
 *
 * @author h.schmidt
 */
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JTable;
import jxl.read.biff.BiffException;
import java.util.Iterator;
import javax.swing.table.TableModel;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class EmailMarketingController {

    /**
     *
     * @param file
     * @param arquivo
     * @return
     * @throws IOException
     * @throws BiffException
     */
    public int processExcelFile(File file) {

        int count = 0;

        try {
            // Criando fluxo de entrada
            FileInputStream myInput = new FileInputStream(file);

            // Crie uma pasta de trabalho usando o sistema de arquivos 
            XSSFWorkbook myWorkBook = new XSSFWorkbook(myInput);

            //Obter a primeira folha de pasta de trabalho 
            XSSFSheet mySheet = myWorkBook.getSheetAt(0);

            /**
             * Nós agora precisamos de algo para percorrer as células.*
             */
            Iterator<Row> rowIter = mySheet.rowIterator();
            while (rowIter.hasNext()) {

                XSSFRow myRow = (XSSFRow) rowIter.next();
                Iterator<org.apache.poi.ss.usermodel.Cell> cellIter = myRow.cellIterator();
                while (cellIter.hasNext()) {

                    XSSFCell myCell = (XSSFCell) cellIter.next();
                    //obter índice da celula
                    System.out.println("Cell column index: " + myCell.getColumnIndex());
                    //obter tipo de célula
                    System.out.println("Cell Type: " + myCell.getCellType());

                    //obter o valor célula
                    switch (myCell.getCellType()) {
                        case XSSFCell.CELL_TYPE_NUMERIC:
                            System.out.println("Cell Value: " + myCell.getNumericCellValue());
                            break;
                        case XSSFCell.CELL_TYPE_STRING:
                            System.out.println("Cell Value: " + myCell.getStringCellValue());
                            break;
                        default:
                            System.out.println("Cell Value: " + myCell.getRawValue());
                            break;
                    }
                    System.out.println("---");

                    if (myCell.getColumnIndex() == 0
                            && !myCell.getStringCellValue().trim().equals("")
                            && !myCell.getStringCellValue().trim().equals("Item Number")) {
                        count++;
                    }

                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return count;

    }

    public void exportExcelFile(JTable table, File file) throws IOException {
        TableModel model = table.getModel();
        FileWriter out = new FileWriter(file);
        try (BufferedWriter bw = new BufferedWriter(out)) {
            for (int x = 0; x < model.getColumnCount(); x++) {
                bw.write(model.getColumnName(x) + "\t");
            }
            bw.write("\n");

            for (int x = 0; x < model.getColumnCount(); x++) {
                for (int y = 0; y < model.getColumnCount(); y++) {
                    bw.write(model.getValueAt(x, y).toString() + "\t");
                }
                bw.write("\n");
            }
        }
        System.out.print("Write out to " + **fil**e);
    }

}

Já tentei debugar com o NetBeans e a olho, ja procurei e não estou conseguindo compreender pois tudo parece dentro dos conformes.

Preciso da ajuda de vocês !

Muito obrigado.

  1. Você vai ver essas setas em qualquer página de pergunta. Com elas, você pode dizer se uma pergunta ou uma resposta foram relevantes ou não.
  2. Edite sua pergunta ou resposta caso queira alterar ou adicionar detalhes.
  3. Caso haja alguma dúvida sobre a pergunta, adicione um comentário. O espaço de respostas deve ser utilizado apenas para responder a pergunta.
  4. Se o autor da pergunta marcar uma resposta como solucionada, esta marca aparecerá.
  5. Clique aqui para mais detalhes sobre o funcionamento do GUJ!

1 resposta

Não é a resposta que estava procurando? Procure outras perguntas com as tags java netbeans arquivos ou faça a sua própria pergunta.