[RESOLVIDO] Erro ao exportar para excel

A tabela preenche, eu consigo trazer os dados do BD normalmente, o problema está na hora de exportar com documento

Segundo a impressão de erro o meu problema está na linha dentro do meu for, eu já instanciei a variavel i e j com valor de 0 cada um respectivamente

public void toExcel(JTable table, File file) throws IOException {  // auxilia o metodo a cima
        TableModel model = table.getModel();
        FileWriter excel;
            try {
                excel = new FileWriter(file);
                for (int i = 0; i < model.getColumnCount(); i++) {
                    excel.write(model.getColumnName(i) + "\t");
                }
                excel.write("\n");
                for (int i = 0; i < model.getRowCount(); i++) {
                    for (int j = 0; j < model.getColumnCount(); j++) {
                        excel.write(model.getValueAt(i, j).toString() + "\t");
//O erro está ocorrendo na linha acima 
                    }
                    excel.write("\n");
                }
                excel.close();
                JOptionPane.showMessageDialog(null, "Salvo em: " + file);
                System.out.println("Salvo em: " + file);
            } catch (java.io.IOException | NullPointerException ex) {
                ex.printStackTrace();
            }
    }

public void exportarExcel(JTable table) {  // salva a um jtable em xls
        {
            JFileChooser fc = new JFileChooser();
            int option = fc.showSaveDialog(table);  // da erro aqui
            if (option == JFileChooser.APPROVE_OPTION) {
                String filename = fc.getSelectedFile().getName();
                String path = fc.getSelectedFile().getParentFile().getPath();
                int len = filename.length();
                String ext = "";
                String file = "";
                if (len > 4) {
                    ext = filename.substring(len - 4, len);
                }
                if (ext.equals(".xls")) {
                    file = path + "\\" + filename;
                } else {
                    file = path + "\\" + filename + ".xls";
                }
                if (ext.equals(".xlsx")) {
                    file = path + "\\" + filename;
                } else {
                    file = path + "\\" + filename + ".xlsx";
                }
                try {
                    toExcel(table, new File(file));
                } catch (IOException ex) {
                }
            }
        }
    }


    java.lang.NullPointerException
	at VisionMenus.TelaRelGeral.toExcel(TelaRelGeral.java:276)
	at VisionMenus.TelaRelGeral.exportarExcel(TelaRelGeral.java:254)
	at VisionMenus.TelaRelGeral.JBExportarActionPerformed(TelaRelGeral.java:99)
	at VisionMenus.TelaRelGeral.access$000(TelaRelGeral.java:25)
	at VisionMenus.TelaRelGeral$1.actionPerformed(TelaRelGeral.java:83)
	at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
	at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
	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:6539)
	at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
	at java.awt.Component.processEvent(Component.java:6304)
	at java.awt.Container.processEvent(Container.java:2239)
	at java.awt.Component.dispatchEventImpl(Component.java:4889)
	at java.awt.Container.dispatchEventImpl(Container.java:2297)
	at java.awt.Component.dispatchEvent(Component.java:4711)
	at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4904)
	at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4535)
	at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4476)
	at java.awt.Container.dispatchEventImpl(Container.java:2283)
	at java.awt.Window.dispatchEventImpl(Window.java:2746)
	at java.awt.Component.dispatchEvent(Component.java:4711)
	at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:760)
	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$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
	at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:84)
	at java.awt.EventQueue$4.run(EventQueue.java:733)
	at java.awt.EventQueue$4.run(EventQueue.java:731)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
	at java.awt.EventQueue.dispatchEvent(EventQueue.java:730)
	at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:205)
	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)

Boa. o seu problema é esse TableModel, testei seu código aqui e deu certo.

    public void toExcel(JTable tabela, File file) { //Não há necessidade do Throws quando se tem o Try-Catch
    //Apaga a linha TableMoel
    FileWriter excel;
    try {
        excel = new FileWriter(file);
        for (int i = 0; i < tabela.getColumnCount(); i++) { //Troquei o model por tabela, agora vai rodar.
            excel.write(tabela.getColumnName(i) + "\t");
        }
        excel.write("\n");
        for (int i = 0; i < tabela.getRowCount(); i++) {
            for (int j = 0; j < tabela.getColumnCount(); j++) {
                excel.write(tabela.getValueAt(i, j).toString() + "\t");
            }
            excel.write("\n");
        }
        excel.close();
        JOptionPane.showMessageDialog(null, "Salvo em: " + file);
        System.out.println("Salvo em: " + file);
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

Na hora de chamar:

toExcel(tabela, new File("C:\\Nova Pasta\\arquivo.xls")); //tabela é o nome da minha jTable

Ué, pq dois métodos? Só um resolve.

Na verdade esse segundo serve para eu escolher o lugar onde irei salvar o arquivo

se eu já informar o caminho o arquivo só será salvo naquele lugar

pelo que eu entendi é isso

e ele escolhe o formato xls que será salvo

Beleza, mas já testou método?

Continua dando NullPointer

java.lang.NullPointerException
	at VisionMenus.TelaRelGeral.toExcel(TelaRelGeral.java:275)
	at VisionMenus.TelaRelGeral.JBExportarActionPerformed(TelaRelGeral.java:100)
	at VisionMenus.TelaRelGeral.access$000(TelaRelGeral.java:25)
	at VisionMenus.TelaRelGeral$1.actionPerformed(TelaRelGeral.java:83)
	at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
	at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
	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:6539)
	at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
	at java.awt.Component.processEvent(Component.java:6304)
	at java.awt.Container.processEvent(Container.java:2239)
	at java.awt.Component.dispatchEventImpl(Component.java:4889)
	at java.awt.Container.dispatchEventImpl(Container.java:2297)
	at java.awt.Component.dispatchEvent(Component.java:4711)
	at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4904)
	at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4535)
	at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4476)
	at java.awt.Container.dispatchEventImpl(Container.java:2283)
	at java.awt.Window.dispatchEventImpl(Window.java:2746)
	at java.awt.Component.dispatchEvent(Component.java:4711)
	at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:760)
	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$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
	at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:84)
	at java.awt.EventQueue$4.run(EventQueue.java:733)
	at java.awt.EventQueue$4.run(EventQueue.java:731)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
	at java.awt.EventQueue.dispatchEvent(EventQueue.java:730)
	at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:205)
	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)


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

        //exportarExcel(JTGeralIndice);
        toExcel(JTGeralIndice, new File("C:\\Users\\Desktop\\arquivo.xlsx"));

    }        

public void toExcel(JTable tabela, File file) {  

        FileWriter excel;
        
            try {
                excel = new FileWriter(file);
                for (int i = 0; i < tabela.getColumnCount(); i++) {
                    excel.write(tabela.getColumnName(i) + "\t");
                }

                excel.write("\n");
                for (int i = 0; i < tabela.getRowCount(); i++) {
                    for (int j = 0; j < tabela.getColumnCount(); j++) {
                        excel.write(tabela.getValueAt(i, j).toString() + "\t");
                    }
                    excel.write("\n");
                }

                excel.close();
                JOptionPane.showMessageDialog(null, "Salvo em: " + file);
                System.out.println("Salvo em: " + file);
            } catch (java.io.IOException | NullPointerException ex) {
                ex.printStackTrace();
            }

    }

E para o meu programa eu prefiro chamar o exportarExcel, pois como falei ele me dá a opção de abrir uma caixa de diálogo em que eu possa escolher o lugar onde irei salvar

123131

Então faz tudo no mesmo método:

public void salvarArquivo(JTable tabela) {
    FileWriter excel;
    JFileChooser chooser = new JFileChooser("C:\\"); //pasta predefinida
    chooser.setDialogTitle("Salve o arquivo");
    chooser.showSaveDialog((this));
    File f = chooser.getSelectedFile();
    if (!f.getAbsolutePath().endsWith(".xls")) {
        f = new File(f.getAbsolutePath() + ".xls");
    }
    try {
        excel = new FileWriter(f);
        for (int i = 0; i < tabela.getColumnCount(); i++) { //Troquei o model por tabela, agora vai rodar.
            excel.write(tabela.getColumnName(i) + "\t");
        }
        excel.write("\n");
        for (int i = 0; i < tabela.getRowCount(); i++) {
            for (int j = 0; j < tabela.getColumnCount(); j++) {
                excel.write(tabela.getValueAt(i, j).toString() + "\t");
            }
            excel.write("\n");
        }
        excel.close();
        System.out.println("Salvo em: " + f);
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

Onde você executou o método que eu te mandei? Porquê não tem como dar NullPointer, a menos que a tabela esteja vazia.

Eu executei dentro de um Button

JB = Java Button

OK, mas só há possibilidade de erro se a tabela estiver vazia, porquê eu testei aqui e funcionou.

O que tem nessa linha?

at VisionMenus.TelaRelGeral.toExcel(TelaRelGeral.java:275)
private void JBExportarActionPerformed(java.awt.event.ActionEvent evt) {                                           
    //Button que recebe o método
    //exportarExcel(JTGeralIndice);
    //toExcel(JTGeralIndice, new File("C:\\Users\\LICITA\\Desktop\\arquivo.xlsx"));
    salvarArquivo(JTGeralIndice);
}    

.

 public TelaRelGeral() {
        initComponents();

        conecta.conexao();

        preenchertabela("select * from indice_licipa order by id_indice");
       // chamando o método preencher tabela
    }

  private void preenchertabela(String SQL) {
  //método preencher tabela (traz os dados do BD e seta na table)

        ArrayList dados = new ArrayList();
        String[] Colunas = new String[]{"1-N_Proces", "2-Modal", "3-N_Modal", "4-Emis", "5-Abert", "6-Dia", "7-Mes", "8-Ano", "9-Objet", "10-Venc", "11-Cpf/Cnpj", "12-N_Cont", "13-DT_Cont", "14-Val_Cont", "15-Vigen", "16-Orgão", "17-Unid", "18-Gest"};
        conecta.executaSQL(SQL);

        try {
            conecta.rs.first();

            do {
                dados.add(new Object[]{conecta.rs.getString("nprocesso_indice"), conecta.rs.getString("modalidade_indice"), conecta.rs.getString("nmodalidade_indice"), conecta.rs.getString("emissao_indice"), conecta.rs.getString("abertura_indice"), conecta.rs.getString("fk_inddia"), conecta.rs.getString("fk_indmes"), conecta.rs.getString("fk_indano"), conecta.rs.getString("objeto_indice"), conecta.rs.getString("vencedor_indice"), conecta.rs.getString("cpfcnpj_indice"), conecta.rs.getString("ncontrato_indice"), conecta.rs.getString("dtcontrato_indice"), conecta.rs.getString("valorcontrato_indice"), conecta.rs.getString("vigencia_indice"), conecta.rs.getString("fk_indori"), conecta.rs.getString("fk_induni"), conecta.rs.getString("gestor_indice")});

            } while (conecta.rs.next());
        } catch (SQLException ex) {
            Logger.getLogger(TelaRelGeral.class.getName()).log(Level.SEVERE, null, ex);
        }

        ModTab mt = new ModTab(dados, Colunas);
        JTGeralIndice.setModel(mt);

        JTGeralIndice.getColumnModel().getColumn(0).setPreferredWidth(70);
        JTGeralIndice.getColumnModel().getColumn(0).setResizable(false);

        JTGeralIndice.getColumnModel().getColumn(1).setPreferredWidth(70);
        JTGeralIndice.getColumnModel().getColumn(1).setResizable(false);

        JTGeralIndice.getColumnModel().getColumn(2).setPreferredWidth(70);
        JTGeralIndice.getColumnModel().getColumn(2).setResizable(false);

        JTGeralIndice.getColumnModel().getColumn(3).setPreferredWidth(70);
        JTGeralIndice.getColumnModel().getColumn(3).setResizable(false);

        JTGeralIndice.getColumnModel().getColumn(4).setPreferredWidth(70);
        JTGeralIndice.getColumnModel().getColumn(4).setResizable(false);

        JTGeralIndice.getColumnModel().getColumn(5).setPreferredWidth(70);
        JTGeralIndice.getColumnModel().getColumn(5).setResizable(false);

        JTGeralIndice.getColumnModel().getColumn(6).setPreferredWidth(70);
        JTGeralIndice.getColumnModel().getColumn(6).setResizable(false);

        JTGeralIndice.getColumnModel().getColumn(7).setPreferredWidth(70);
        JTGeralIndice.getColumnModel().getColumn(7).setResizable(false);

        JTGeralIndice.getColumnModel().getColumn(8).setPreferredWidth(400);
        JTGeralIndice.getColumnModel().getColumn(8).setResizable(false);

        JTGeralIndice.getColumnModel().getColumn(9).setPreferredWidth(70);
        JTGeralIndice.getColumnModel().getColumn(9).setResizable(false);

        JTGeralIndice.getTableHeader().setReorderingAllowed(false);
        JTGeralIndice.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        JTGeralIndice.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    }

.

public void salvarArquivo(JTable tabela) {
//metódo que salva o dados da table em um documento xls
    FileWriter excel;
    JFileChooser chooser = new JFileChooser("C:\\"); //pasta predefinida
    chooser.setDialogTitle("Salve o arquivo");
    chooser.showSaveDialog((this));
    File f = chooser.getSelectedFile();
    if (!f.getAbsolutePath().endsWith(".xls")) {
        f = new File(f.getAbsolutePath() + ".xls");
    }
    try {
        excel = new FileWriter(f);
        for (int i = 0; i < tabela.getColumnCount(); i++) { //Troquei o model por tabela, agora vai rodar.
            excel.write(tabela.getColumnName(i) + "\t");
        }
        excel.write("\n");
        for (int i = 0; i < tabela.getRowCount(); i++) {
            for (int j = 0; j < tabela.getColumnCount(); j++) {
                excel.write(tabela.getValueAt(i, j).toString() + "\t");
            }
            excel.write("\n");
        }
        excel.close();
        System.out.println("Salvo em: " + f);
    } catch (java.io.IOException | NullPointerException ex) {
        ex.printStackTrace();
    }
}

Erro:

run:
java.lang.NullPointerException
	at VisionMenus.TelaRelGeral.salvarArquivo(TelaRelGeral.java:298)
	at VisionMenus.TelaRelGeral.JBExportarActionPerformed(TelaRelGeral.java:93)
	at VisionMenus.TelaRelGeral.access$000(TelaRelGeral.java:17)
	at VisionMenus.TelaRelGeral$1.actionPerformed(TelaRelGeral.java:75)

// linha de erro nº 298

 excel.write(tabela.getValueAt(i, j).toString() + "\t");

tem alguma linha vazia?

não. mandei junto (apesar de ter ficado bagunçado) o meu método que exporta os dados do BD e passa pra table também pra vc ter uma ideia melhor do processo

Cara, tem linha vazia sim, senão ele não dava esse erro. Quando for mandar código, seleciona ele e aperta CTRL+SHIFT+C, fica muito ilegível do que jeito você colocou.

public void salvarArquivo(JTable tabela) {
    FileWriter excel;
    JFileChooser chooser = new JFileChooser("C:\\"); //pasta predefinida
    chooser.setDialogTitle("Salve o arquivo");
    chooser.showSaveDialog((this));
    File f = chooser.getSelectedFile();
    if (!f.getAbsolutePath().endsWith(".xls")) {
        f = new File(f.getAbsolutePath() + ".xls");
    }
    try {
        excel = new FileWriter(f);
        for (int i = 0; i < tabela.getColumnCount(); i++) {
            excel.write(tabela.getColumnName(i) + "\t");
        }
        excel.write("\n");
        for (int i = 0; i < tabela.getRowCount(); i++) {
            for (int j = 0; j < tabela.getColumnCount(); j++) {
                try {
                    excel.write(tabela.getValueAt(i, j).toString() + "\t");
                } catch (NullPointerException e) {

                }
            }
            excel.write("\n");
        }
        excel.close();
        System.out.println("Salvo em: " + f);
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

Pronto, funcionou
Vlew, obrigadão

pode fechar o tópico

1 curtida