Adicionales.Abrir_xml.java Source code

Java tutorial

Introduction

Here is the source code for Adicionales.Abrir_xml.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Adicionales;

import java.awt.Desktop;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import static pantallaprin.principal.dskPrin;

/**
 *
 * @author usuario
 */
public class Abrir_xml extends InternalFrameImagen {

    private String strRut = "C:\\";
    public String tipo_comprobante;
    public List<String> archivos;
    public List<String> nombres;

    /**
    * Creates new form Abrir_xml
    */

    public Abrir_xml() {
        initComponents();
        setImage("/imagenes/fondosef.jpg");
        archivos = new ArrayList<>();
        nombres = new ArrayList<>();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        AbrExpoXls = new javax.swing.JButton();
        AbrGuardCom = new javax.swing.JButton();
        AbrProp = new javax.swing.JButton();
        AbrCer = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        txaAbrFacXlm = new javax.swing.JPanel();

        setClosable(true);
        setIconifiable(true);
        setMaximizable(true);
        setTitle("Transformar .xml a .xls");
        setToolTipText("");
        setFrameIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/tes.jpg"))); // NOI18N
        setOpaque(true);

        AbrExpoXls.setText("Exportar .xls");
        AbrExpoXls.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AbrExpoXlsActionPerformed(evt);
            }
        });

        AbrGuardCom.setText("Guardar Como ...");
        AbrGuardCom.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AbrGuardComActionPerformed(evt);
            }
        });

        AbrProp.setText("Propiedades");
        AbrProp.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AbrPropActionPerformed(evt);
            }
        });

        AbrCer.setText("Cerrar");
        AbrCer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AbrCerActionPerformed(evt);
            }
        });

        txaAbrFacXlm.setAutoscrolls(true);
        txaAbrFacXlm.setLayout(new java.awt.GridLayout(0, 1));
        jScrollPane1.setViewportView(txaAbrFacXlm);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup().addContainerGap(28, Short.MAX_VALUE)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 347,
                                javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(AbrGuardCom, javax.swing.GroupLayout.Alignment.LEADING,
                                        javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
                                        Short.MAX_VALUE)
                                .addComponent(AbrExpoXls, javax.swing.GroupLayout.Alignment.LEADING,
                                        javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
                                        Short.MAX_VALUE)
                                .addComponent(AbrProp, javax.swing.GroupLayout.Alignment.LEADING,
                                        javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
                                        Short.MAX_VALUE)
                                .addComponent(AbrCer, javax.swing.GroupLayout.Alignment.LEADING,
                                        javax.swing.GroupLayout.PREFERRED_SIZE, 117,
                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(26, 26, 26)));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup().addGap(30, 30, 30)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jScrollPane1)
                                .addGroup(layout.createSequentialGroup().addComponent(AbrExpoXls).addGap(32, 32, 32)
                                        .addComponent(AbrGuardCom).addGap(32, 32, 32).addComponent(AbrProp)
                                        .addGap(32, 32, 32).addComponent(AbrCer)))
                        .addGap(41, 41, 41)));

        setBounds(0, 0, 552, 288);
    }// </editor-fold>//GEN-END:initComponents

    private void AbrGuardComActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AbrGuardComActionPerformed
        guardarDirXls(); // TODO add your handling code here:
    }//GEN-LAST:event_AbrGuardComActionPerformed

    private void AbrPropActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AbrPropActionPerformed
        Archivo.ProPanEti1 objProp = new Archivo.ProPanEti1();
        dskPrin.add(objProp, JLayeredPane.DEFAULT_LAYER);
        objProp.setVisible(true);
    }//GEN-LAST:event_AbrPropActionPerformed

    private void AbrCerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AbrCerActionPerformed
        this.dispose(); // TODO add your handling code here:
    }//GEN-LAST:event_AbrCerActionPerformed

    private void AbrExpoXlsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AbrExpoXlsActionPerformed
        JOptionPane d = null;
        if (JOptionPane.showConfirmDialog(this,
                "<html>Seguro que desea convertir<br>los archivos a formatos XLS?</html>",
                "Facturacin Electrnica TES", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
            guardarDirXls();
        }
    }//GEN-LAST:event_AbrExpoXlsActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton AbrCer;
    private javax.swing.JButton AbrExpoXls;
    private javax.swing.JButton AbrGuardCom;
    private javax.swing.JButton AbrProp;
    private javax.swing.JScrollPane jScrollPane1;
    public javax.swing.JPanel txaAbrFacXlm;
    // End of variables declaration//GEN-END:variables

    private void ExportarEtiquetasXml(HSSFWorkbook workbook, Document document, String nombre) {
        System.out.println("Exportando : " + nombre);
        try {
            HSSFSheet sheet = workbook.createSheet(tipo_comprobante + " " + (nombres.indexOf(nombre) + 1));
            System.out.println("Primera vez creada");
            HSSFCellStyle cellStyle = workbook.createCellStyle();
            HSSFRow rowTag = sheet.createRow(0);
            HSSFRow RowData = sheet.createRow(1);
            NodeList nodeList = document.getElementsByTagName("*");
            for (int i = 0; i < nodeList.getLength(); i++) {
                Element element = (Element) nodeList.item(i);
                if (element.getChildNodes().getLength() == 1 && !element.getNodeName().contains(":")) {
                    if (element.getFirstChild().getNodeType() == Node.TEXT_NODE
                            && !element.getNodeName().equals("comprobante")) {
                        HSSFCell cellTag = rowTag.createCell(i);
                        cellTag.setCellValue(element.getNodeName());
                        HSSFCell cellData = RowData.createCell(i);
                        cellData.setCellValue(element.getFirstChild().getNodeValue());
                        sheet.autoSizeColumn((short) i);
                        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
                        cellTag.setCellStyle(cellStyle);
                    } else {
                        DocumentBuilderFactory sub_factory = DocumentBuilderFactory.newInstance();
                        DocumentBuilder sub_builder = sub_factory.newDocumentBuilder();
                        Document sub_document = sub_builder
                                .parse(new InputSource(new StringReader(element.getFirstChild().getNodeValue())));
                        NodeList sub_nodeList = sub_document.getElementsByTagName("*");
                        for (int j = 0; j < sub_nodeList.getLength(); j++) {
                            Element sub_element = (Element) sub_nodeList.item(j);
                            if (sub_element.getNodeName().equals("Signature"))
                                break;
                            if (sub_element.getChildNodes().getLength() == 1
                                    && !sub_element.getNodeName().contains(":")) {
                                if (sub_element.getFirstChild().getNodeType() == Node.TEXT_NODE) {
                                    HSSFCell cellTag = rowTag.createCell(j);
                                    cellTag.setCellValue(sub_element.getNodeName());
                                    HSSFCell cellData = RowData.createCell(j);
                                    cellData.setCellValue(sub_element.getFirstChild().getNodeValue());
                                    sheet.autoSizeColumn((short) j);
                                    cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
                                    cellTag.setCellStyle(cellStyle);
                                }
                            }
                        }
                    }
                }
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
        } catch (IllegalArgumentException e) {
            JOptionPane.showMessageDialog(null, "<html>Error al exportar archivo " + nombre
                    + "<br>Verificar maximo de etiquetas soportadas [255]</html>");
        } catch (ParserConfigurationException e) {
            System.out.println("ParserConfigurationException " + e.getMessage());
        } catch (SAXException e) {
            System.out.println("SAXException " + e.getMessage());
        }
    }

    private boolean guardarArcXls(String strNomArc, List<String> archivos) {
        boolean blnRes = true;

        try {
            // Se crea un nuevo libro de trabajo de EXCEL
            HSSFWorkbook workbook = new HSSFWorkbook();
            for (String archivo_n : archivos) {
                //cargamos el contenido del n-simo contenido
                File fileXML = new File(archivo_n);
                // Definimos una nueva instancia de un API para generar arbol XML
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                // Definimos nuevo arbol XML
                DocumentBuilder builder = factory.newDocumentBuilder();
                // Representamos el archivo XML especificado en el arbol
                Document document = builder.parse(fileXML);
                //System.out.println("etiquetar archivo "+archivos.indexOf(archivo_n)+" de "+nombres.size());
                ExportarEtiquetasXml(workbook, document, nombres.get(archivos.indexOf(archivo_n)));

            }
            try (FileOutputStream output = new FileOutputStream(new File(strNomArc))) {
                workbook.write(output);
            }
            Desktop.getDesktop().open(new File(strNomArc));

        } catch (FileNotFoundException e) {
            System.out.println(e.getMessage());
        } catch (IOException e) {
            System.out.println(e.getMessage());
        } catch (ParserConfigurationException e) {
            System.out.println("ParserConfigurationException " + e.getMessage());
        } catch (SAXException e) {
            System.out.println("SAXException " + e.getMessage());
        }

        return blnRes;
    }

    private void guardarDirXls() {
        try {
            String strArc;
            JFileChooser objFilCho = new JFileChooser();
            objFilCho.setDialogTitle("Guardar Como");
            objFilCho.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
            objFilCho.setCurrentDirectory(new File(strRut));
            FileNameExtensionFilter objFilNamExt = new FileNameExtensionFilter("Archivos.xls", "xls", "XLS");
            objFilCho.setFileFilter(objFilNamExt);
            if (objFilCho.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
                strRut = objFilCho.getCurrentDirectory().getAbsolutePath() + "\\";
                strArc = objFilCho.getSelectedFile().getPath();
                //Si no tiene la extensin "xls" agregarsela.
                if (!strArc.toLowerCase().endsWith(".xls"))
                    strArc += ".xls";
                if (guardarArcXls(strArc, archivos))
                    ((Abrir_xml) dskPrin.getSelectedFrame()).setTitle(strArc);
            } else
                System.out.println("El usuario cancel");
        } catch (Exception e) {
            System.out.println("Excepcin: " + e.toString());
        }
    }

}