[RESOLVIDO] Exportar para o excel, arquivo fica em aberto. Como resolver?

Bom dia amigos, tenho uma Jtable e uso um comando para exportar dados dela para um arquivo em Excel. O problema é que quando vou abrir esse arquivo que criei, ele diz que só posso abrir em modo de leitura, pois já está sendo usado na aplicação Java.
Como posso criar este arquivo e depois de criar mandar um comanda de fechar ou para de usar o arquivo. Para não dar mais esta mensagem de “em aberto”?

manda o seu código

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

int rows = tabelaMembros.getModel().getRowCount(); 
  if (rows > 0) {

JFileChooser seleccionar = new JFileChooser();

File arquivo;

if (seleccionar.showDialog(null, "Exportar Excel") == JFileChooser.APPROVE_OPTION) {
    
    arquivo = seleccionar.getSelectedFile();            
    int cantFila = tabelaMembros.getRowCount();
    int cantColumna = tabelaMembros.getColumnCount();
   
    Workbook wb;
    wb = new HSSFWorkbook();
    Sheet folha = wb.createSheet("  ");
    try {
        for (int i = -1; i <cantFila; i++) {                
            Row fila = folha.createRow(i+1);                
            for (int j = 0;j<cantColumna; j++) {                    
                Cell celda = fila.createCell(j);                    
                if(i==-1) {    
                    celda.setCellValue(String.valueOf(tabelaMembros.getColumnName(j)));
                } else {                        
                   celda.setCellValue(String.valueOf(tabelaMembros.getValueAt(i, j)));     
                }
                wb.write(new FileOutputStream(arquivo + ".xls"));
            }
        }
        
        JOptionPane.showMessageDialog(null, "Planilha exportada com sucesso.");
        
        int resposta = 0;
    resposta = JOptionPane.showConfirmDialog(null, "Deseja abrir o arquivo?", "AVISO", 0, 2);
    if (resposta == JOptionPane.YES_OPTION) {
        
        File excel = new File(arquivo + ".xls");
        try {
            Desktop.getDesktop().open(excel);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Erro ao Abrir: " + ex);
        }
    }
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, "Por favor tente novamente"+e);
    }

} else {
    JOptionPane.showMessageDialog(null, "Erro ao Exportar Planilha....");
}  


 }else{
  
      JOptionPane.showMessageDialog(null, "Busque alguma informação antes de Exportar!!"); 
  
  }   // fim do if

             
        
}
1 curtida

Faltou o close do fileoutstream e do workbook. Faz assim:

        FileOutputStream fileOut = new FileOutputStreamm("arquivo.xlsx");
        wb.write(fileOut);
        fileOut.close();

A cada iteração você está gravando um arquivo, não faz isso amiguinho…
Faz assim que deve resolver seu problema:

    for (int i = -1; i <cantFila; i++) {                
        Row fila = folha.createRow(i+1);                
        for (int j = 0;j<cantColumna; j++) {                    
            Cell celda = fila.createCell(j);                    
            if(i==-1) {    
                celda.setCellValue(String.valueOf(tabelaMembros.getColumnName(j)));
            } else {                        
               celda.setCellValue(String.valueOf(tabelaMembros.getValueAt(i, j)));     
            }
        }
    }
    OutputStream saida = new FileOutputStream(arquivo + ".xls");
    wb.write(saida); // grava o arquivo após sair do laço
    saida.flush();
    saida.close(); // fecha o arquivo

Exatamente, ele também precisa mover esse código pra fora dos laços, senão ele vai regravar o arquivo a cada célula setada.

1 curtida

Valeu mesmo, deu super Certo! Obrigado por compartilhar o conhecimento de voces!

1 curtida