0 votes

Export JTable to extensions .xlsx and .pdf

Good day, I made a JFrame Form which you have to export a jTable to Excel, and PDF. I already exports but exports 2 files at a time, then I want you to select the filter to Excel in the FileChooser, I can export only in that extension, the same with the pdf.

I leave you the code of the export, thanks in advance.

Solved after placing if (nameExtension.equals("Documento PDF (*.pdf)"))

  seleccionar.addChoosableFileFilter(new FileNameExtensionFilter("Documento PDF (*.pdf)", "pdf"));
        seleccionar.addChoosableFileFilter(new FileNameExtensionFilter("Libro de Excel (*.xlsx)", "xlsx"));
        seleccionar.setAcceptAllFileFilterUsed(false);

        if (seleccionar.showDialog(null, "Exportar Archivo") == JFileChooser.APPROVE_OPTION) {

            String nameExtension = seleccionar.getFileFilter().getDescription();

            // Exportar a PDF
            if (nameExtension.equals("Documento PDF (*.pdf)")) {
                try {
                    // We create the document and set the file name.        
                    // Creamos el documento e indicamos el nombre del fichero.
                    Document document = new Document();
                    try {
                        PdfWriter.getInstance(document, new FileOutputStream(seleccionar.getSelectedFile() + ".pdf"));
                    } catch (FileNotFoundException fileNotFoundException) {

                    }
                    document.open();

                    // First page (Primera página)
                    Anchor anchor = new Anchor();
                    anchor.setName("");

                    // Second parameter is the number of the chapter (El segundo parámetro es el número del capí­tulo).
                    Chapter catPart = new Chapter(new Paragraph(anchor), 1);

                    Paragraph subPara = new Paragraph("");
                    Section subCatPart = catPart.addSection(subPara);
                    subCatPart.add(new Paragraph(""));

                    // Create the table (Creamos la tabla)
                    PdfPTable table = new PdfPTable(jTable1.getColumnCount());

                    // Now we fill the rows of the PdfPTable (Ahora llenamos las filas de PdfPTable)
                    PdfPCell columnHeader;
                    // Fill table columns header 
                    // Rellenamos las cabeceras de las columnas de la tabla.                
                    for (int column = 0; column < jTable1.getColumnCount(); column++) {
                        columnHeader = new PdfPCell(new Phrase(jTable1.getColumnName(column)));
                        columnHeader.setHorizontalAlignment(Element.ALIGN_CENTER);
                        table.addCell(columnHeader);
                    }
                    table.setHeaderRows(1);
                    // Fill table rows (rellenamos las filas de la tabla).                
                    for (int row = 0; row < jTable1.getRowCount(); row++) {
                        for (int column = 0; column < jTable1.getColumnCount(); column++) {
                            table.addCell(jTable1.getValueAt(row, column).toString());
                        }
                    }
                    subCatPart.add(table);

                    document.add(catPart);

                    document.close();
                    JOptionPane.showMessageDialog(this.jTable1, "Your PDF file has been generated!(¡Se ha generado tu hoja PDF!)",
                            "RESULTADO", JOptionPane.INFORMATION_MESSAGE);
                } catch (DocumentException documentException) {
                    System.out.println("The file not exists (Se ha producido un error al generar un documento): " + documentException);
                    JOptionPane.showMessageDialog(this.jTable1, "The file not exists (Se ha producido un error al generar un documento): " + documentException,
                            "ERROR", JOptionPane.ERROR_MESSAGE);
                }
            }
            // Exportar a EXCEL
            if (nameExtension.equals("Libro de Excel (*.xlsx)")) {
                File archivo;
                archivo = seleccionar.getSelectedFile();
                int cantFila = jTable1.getRowCount();
                int cantColumna = jTable1.getColumnCount();
                Workbook wb;
                wb = new XSSFWorkbook();
                Sheet hoja = wb.createSheet(" ");

                try {
                    for (int i = 0; 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(jTable1.getColumnName(j)));
                            } else {
                                celda.setCellValue(String.valueOf(jTable1.getValueAt(i, j)));
                            }
                            wb.write(new FileOutputStream(archivo + ".xlsx"));
                        }
                    }
                    JOptionPane.showMessageDialog(null, "Exportacion exitosa");
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(null, "Vuelve a intentarlo");
                }
            }
        }

0voto

Dev. Joel Points 20672

You could check the extensión the file, and hence be able to verify which format you will export your jTable , I did use a regular expression to get the extension , if you have a better way the replace

In your case call to your métodos to export, depending on the extensión.

In addition to use a variable booleana to have control when you choose a length unknown or when they do not choose anything.

boolean active=false;
  while(!active)
  {
    if (seleccionar.showDialog(null, "Exportar Archivo") == JFileChooser.APPROVE_OPTION) {
       String extension = seleccionar.getSelectedFile().getAbsolutePath().split("\\.(?=[^\\.]+$)")[1];
       switch(extension){
           case "pdf" : System.out.println("EXPORT PDF");active=true;break;
           case "xlsx" : System.out.println("EXPORT EXCEL");active=true;break;
           default:
               active = JOptionPane.showConfirmDialog(null, "EXTENSIÓN NO VÁLIDA , DESEA SELECCIONAR UNA EXTENSIÓN DIFERENTE?"
                       ,"MENSAJE ! ", JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION;
       }
    }
   else
        active = JOptionPane.showConfirmDialog(null, "NO SELECCIONO UN ARCHIVO, DESEA SELECCIONAR?"
                ,"MENSAJE ! ", JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION;
  }

HolaDevs.com

HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution

Powered by:

X