Export JTable to extensions .xlsx and .pdf

0

Good morning, I made a JFrame Form which has to export a jTable to Excel and PDF. You already export me but you export the 2 files at the time, so I want that when I select the Excel filter in the FileChooser, I export only in that extension, the same with the pdf.

I leave the export code, thanks in advance.

Fixed 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");
                }
            }
        }
    
asked by Camilo Rincón 20.09.2016 в 00:00
source

1 answer

0

You could verify the extensión of the file and there to verify to what format your jTable will be exported, I made use of a regular expression to get the extension, if you have a better way you replace it

In your case you would call your métodos export depending on the extensión .

I also use a variable booleana to have control when choosing an unknown extension or when nothing is chosen.

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;
  }
    
answered by 20.09.2016 в 02:18