Export to Excel - Java

0

This is the code I use to export to excel:

@SuppressWarnings("resource")
    protected void btnExportarExcelActionPerformed(ActionEvent arg0) {
         JFileChooser seleccionar = new JFileChooser();
         File archivo;
         if (seleccionar.showDialog(null, "Exportar a Excel") == JFileChooser.APPROVE_OPTION){
             archivo = seleccionar.getSelectedFile();
             int cantFila = tbNivelArchivo.getRowCount();
             int cantColumna = tbNivelArchivo.getColumnCount();
             XSSFWorkbook wb;
             wb = new XSSFWorkbook();
             Sheet hoja = ((org.apache.poi.ss.usermodel.Workbook) wb).createSheet(" ");
             try {
                    for (int i = -1; i < cantFila; i++) {
                        Row fila = hoja.createRow(i + 1);
                        for (int j = 0; j < cantColumna; j++) {
                            Cell celda = fila.createCell(j);
                            if (i == -1) {
                               celda.setCellValue(String.valueOf(tbNivelArchivo.getColumnName(j)));
                            } else {
                                celda.setCellValue(String.valueOf(tbNivelArchivo.getValueAt(i, j)));
                            }
                            wb.write(new FileOutputStream(archivo + ".xlsx"));
                        }
                    }
                    JOptionPane.showMessageDialog(null, "Exportacion exitosa");
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(null, "Vuelve a intentarlo");
                }
         }
    }

If the excel is generated but it does not open automatically.

    
asked by Bruno 12.01.2017 в 21:50
source

1 answer

2

You can use Desktop.getDesktop ( ) .open (File file) , which according to the documentation opens the file in the associated application.

When you finish generating your file, you call:

Desktop.getDesktop().open(archivo);

And that should open your file in Excel if you have MS Office installed, or Calc if you have LibreOffice, etc.

    
answered by 12.01.2017 в 22:32