Convertir un tableau html en jtable

dodji_phpcs Messages postés 17 Date d'inscription mercredi 22 mars 2006 Statut Membre Dernière intervention 24 avril 2011 - 30 juil. 2009 à 14:21
cs_asle Messages postés 8 Date d'inscription mercredi 23 avril 2008 Statut Membre Dernière intervention 13 septembre 2010 - 31 déc. 2009 à 22:43
Bonjour tous le monde , mon problème est le suivant
J'aimerais récupérer un tableau dans une page html avec java et ensuite le mettre dans un jtable.
S'il y a plusieurs tableau dans cette page html je dois pouvoir choisir quel tableau convertir en jtable.
PS : tout ca doit se faire sans un htmlparser
Merci


Big El Chicano

5 réponses

uhrand Messages postés 491 Date d'inscription samedi 20 mai 2006 Statut Membre Dernière intervention 15 juillet 2012 9
1 août 2009 à 16:37
Tu voudras analyser cet exemple pour commencer:
import java.awt.*;
import java.util.*;
import java.util.regex.*;
import javax.swing.*;
import javax.swing.table.*;
public class HtmlToJTable extends JFrame {
    private String subjectString = "<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">" +
            "<html>" +
            "<head>" +
            "	<title>Untitled</title>" +
            "</head>" +
            "" +
            "\" +
\"----
\" +
\"       test1_1_1, \" +
\"       test1_1_2, \" +
\"\" +
\"----
\" +
\"       test1_2_1, \" +
\"       test1_2_2, \" +
\"\" +
            "
" +
            "\" +
\"----
\" +
\"       test2_1_1, \" +
\"       test2_1_2, \" +
\"\" +
\"----
\" +
\"       test2_2_1, \" +
\"       test2_2_2, \" +
\"\" +
            "
" +
            "" +
            "</html>";
    private String htmlTable;
    public HtmlToJTable() {
        super("HtmlToJTable");
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new FlowLayout());
        setSize(400, 300);
        setLocationRelativeTo(null);
        Pattern regex = Pattern.compile("]*>(.*?)
",
                Pattern.CANON_EQ | Pattern.DOTALL | Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
        Matcher matcher = regex.matcher(subjectString);
        while (matcher.find()) {
            htmlTable = matcher.group();
            if (htmlTable.contains("test2")) {
                JScrollPane scrollPane = new JScrollPane(convertToJTable(htmlTable));
                scrollPane.setPreferredSize(new Dimension(200, 100));
                add(scrollPane);
            }
        }
    }
    private JTable convertToJTable(final String htmlTable) {
        Pattern regexRows = Pattern.compile("<tr[^>]*>(.*?)</tr>",
                Pattern.CANON_EQ | Pattern.DOTALL | Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
        Matcher matcherRows = regexRows.matcher(htmlTable);
        Vector<Vector> dataVector = new Vector<Vector>();
        int columnCount = 0;
        while (matcherRows.find()) {
            for (int i = 1; i <= matcherRows.groupCount(); i++) {
                Vector rowData = new Vector();
                String htmlRow = matcherRows.group(i);
                Pattern regexColumn = Pattern.compile("<td[^>]*>(.*?)</td>",
                        Pattern.CANON_EQ | Pattern.DOTALL | Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
                Matcher matcherColumns = regexColumn.matcher(htmlRow);
                columnCount = 0;
                while (matcherColumns.find()) {
                    for (int j = 1; j <= matcherColumns.groupCount(); j++) {
                        String htmlColumn = matcherColumns.group(j);
                        rowData.add(htmlColumn);
                        columnCount++;
                    }
                }
                dataVector.add(rowData);
            }
        }
        DefaultTableModel model = new DefaultTableModel(0, columnCount);
        for (Vector rowData : dataVector) {
            model.addRow(rowData);
        }
        JTable table = new JTable(model);
        return table;
    }
    public static void main(final String[] args) {
        Runnable gui = new Runnable() {
            public void run() {
                new HtmlToJTable().setVisible(true);
            }
        };
        //GUI must start on EventDispatchThread:
        SwingUtilities.invokeLater(gui);
    }
}
0
dodji_phpcs Messages postés 17 Date d'inscription mercredi 22 mars 2006 Statut Membre Dernière intervention 24 avril 2011
4 août 2009 à 15:32
Merci uhrand pour ta réponse ca m'a aide.
Apparemment tu a travaille avec un string mais moi je dois travaille avec un fichier entier(*.html). En plus les balises <table> n'ont rien qui permet de les distinguer les uns des autres a part leur ordre de parution dans le code. La premiere ligne du tableau doit être le header du jtable.
Un nouvelle difficulté fin d'apparaitre : les colonnes a afficher dans le jtable doit être choisir par l'utilisateur.
Une fois encore merci


Big El Chicano
0
uhrand Messages postés 491 Date d'inscription samedi 20 mai 2006 Statut Membre Dernière intervention 15 juillet 2012 9
4 août 2009 à 18:31
Ne voyant plus aucune question dans ta réponse, je suppose que ton problème est résolu
0
dodji_phpcs Messages postés 17 Date d'inscription mercredi 22 mars 2006 Statut Membre Dernière intervention 24 avril 2011
5 août 2009 à 15:33
Merci j'ai tjrs des problèmes
-au mise de la sélection du tableau a transforme en JTable comme je l'ai dit précédemment on part du fait que rien me permet de distinguer les tableaux les uns des autres.
- En j'aimerais avoir la possibilité de sélectionner les colonnes du tableau qui m'intéresse.

Je vais laisser ce que j'ai essayé de faire, et dis mois ce que tu en penses. Les problèmes évoqués plus haut ne sont pas résolus dans les codes que je laisse

fichier DataFileModel
 */
package Html;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.table.AbstractTableModel;

public class DataFileTableModel extends AbstractTableModel {

    protected Vector data; //données
    protected Vector columnNames; //noms de colonnes
    protected String datafile; //nom du fichier de données
    String ligne;
    int nbColor;
    int sizeTd 0, sizeTr 0;
    //  data = new Vector();
    protected String baliseTd = "<td(.*?)>(.*?)</td>"; //expression reguliere pour la balise <td>
    protected String baliseTr = "<tr(.*?)>";//expression reguliere pour la balise <tr>

    public DataFileTableModel(String f) {
        try {
            datafile = f;
            intTable();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(DataFileTableModel.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(DataFileTableModel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void intTable() throws FileNotFoundException, IOException {
        Matcher mTr, mTd;
        Pattern pTd = Pattern.compile(baliseTd, Pattern.CASE_INSENSITIVE);
        Pattern pTr = Pattern.compile(baliseTr, Pattern.CASE_INSENSITIVE);
        BufferedReader entree = new BufferedReader(new FileReader(datafile));
                data = new Vector();

        do {

            ligne = entree.readLine();
            if (ligne != null) {
                
                mTr = pTr.matcher(ligne);
                mTr.reset();
                while (mTr.find()) {

                    sizeTr++;
                // System.out.println("gildas\n");
                // System.out.println("Trouvé tr" + mTr.group(0));
                // sizeTr++;
                }
                mTd = pTd.matcher(ligne);
                mTd.reset();

                while (mTd.find()) {
                     String htm = "<((.*?))>";
                     String espace = " ";
                    // resultatsTd.add(mTd.group(0));
                    data.addElement( mTd.group(2).replaceAll(htm,"").replaceAll(espace," ").toString().trim());
                   //  data.addElement( "<html>"+mTd.group(2)+"</html>");
                    sizeTd++;
                // System.out.println("gildas\n");
                //     System.out.println("Trouvé " + mTd.group(2));
                //tr++;
                }
            }
        } while (ligne != null);
        entree.close();
        nbColor = sizeTd / sizeTr;
    }

    //    Nombre de lignes
    //Le nombre de lignes est obtenu en divisant le nombre d'éléments du champ data par le nombre de colonnes .
    public int getRowCount() {
        //   System.out.println("getRowcount "+this.getClass() +sizeTd);
        return (sizeTd / getColumnCount());
    }

    public int getColumnCount() {
        return nbColor;
    }

    public String getColumnName(int columnIndex) {
        String colName = "";
        columnNames = new Vector();
        for (int j = 0; j < nbColor; j++) {
            columnNames.add(j, data.elementAt(j));
        //System.out.println(columnNames.elementAt(j));
        }
        if (columnIndex <= getColumnCount()) {
            colName = (String) columnNames.elementAt(columnIndex);
        }
        return colName;
    }

    public Class getColumnClass(int columnIndex) {

       // System.out.println(getValueAt(0,columnIndex).getClass());
         return getValueAt(0,columnIndex).getClass();
    }

    public boolean isCellEditable(int rowIndex, int columnIndex) {
        return true;
    }

    public void setValueAt(Object value, int rowIndex, int columnIndex) {
         int ides = 0;
        ides = (((rowIndex) * getColumnCount()) + (columnIndex));
        data.setElementAt(value,ides);
        fireTableCellUpdated(rowIndex, columnIndex);
    }

    public Object getValueAt(int rowIndex, int columnIndex) {
        int ides = 0;
        ides = (((rowIndex) * getColumnCount()) + (columnIndex));
   //     System.out.println(ides);
     //   System.out.println("rowindex : " + rowIndex + " columnIndex " + columnIndex);
        return (String) data.elementAt(ides);

    }
}



fichier DataFileTable
package Html;

import javax.swing.*;
import java.awt.*;
import java.io.File;

public class DataFileTable extends JPanel  {
     JButton sauve;
    JTable table;
    private JTextField filename new JTextField(),  dir new JTextField();
    private File fichier;

    public DataFileTable(String dataFilePath) {
        // JTable table; // le tableau
        DataFileTableModel model; // le modÃ&#168;le
//fonte
        Font f = new Font("SanSerif", Font.PLAIN, 24);
        setFont(f);
//gestionnaire de positionnement
        setLayout(new BorderLayout());
//construction du modÃ&#168;le de remplissage à partir du fichier
        model = new DataFileTableModel(dataFilePath);
//création du tableau
        table = new JTable();
        table.setAutoResizeMode(5);
        table.setModel(model);
        table.createDefaultColumnsFromModel();

//scroller
        JScrollPane scrollpane = new JScrollPane(table);
        scrollpane.setPreferredSize(new Dimension(600,600));
        //  table.setFillsViewportHeight(true);
        add(scrollpane);
        JFrame fen = new JFrame("Table");
      
        JPanel panel = new JPanel(new BorderLayout());

       // panel.add(btn, BorderLayout.SOUTH);
     
        panel.add(table, BorderLayout.CENTER);
//configuration de la fenêtre
        fen.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        fen.setForeground(Color.black);
        fen.setBackground(Color.lightGray);
        //  fen.getContentPane().add(btn, "Center");
        //fen.getContentPane().add(tablo, "Center");
        fen.getContentPane().add(panel);

        fen.setSize(table.getPreferredSize());
//affichage
        fen.setVisible(true);
//écouteur pour fermeture
        fen.addWindowListener(new WindowCloser());
    }

    //  public void
    public Dimension getPreferredSize() {
        return new Dimension(800, 500);
    }

    public static void main(String args[]) {
//la fenêtre du programme
      
//le tableau
        DataFileTable tablo;
        String nomFichier = "fichier.html";
      //  if (args.length > 0) {
         //   nomFichier = args[0];
        //}
        tablo = new DataFileTable(nomFichier);
        
    }

    
}

WindowCloser

package Html;

import java.awt.Window;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

class WindowCloser extends WindowAdapter {

    public void windowClosing(WindowEvent e) {
        Window win = e.getWindow();
//effacer la fenêtre
        win.setVisible(false);
//terminer le programme
        System.exit(0);
    }
}

un exemple du fichier html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head>


<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Document sans nom</title>
</head>
Voici la liste des étudiants de L3 informatique en 2008/09.


Num.,
Nom Prénom,
Adresse électronique,
Identifiant,
Année,

----

1,
Nom1,
mmon1@adresse.com,
as803819,
2008,

----

2,
Nom2 prenom2_1 prenom2_2,
nom2@adresse.com,
as805431,
2008

</html


Big El Chicano
0

Vous n’avez pas trouvé la réponse que vous recherchez ?

Posez votre question
cs_asle Messages postés 8 Date d'inscription mercredi 23 avril 2008 Statut Membre Dernière intervention 13 septembre 2010
31 déc. 2009 à 22:43
salut,

Mon probleme est comment extraire à partir d'une pabe web seulement les tableaux et les convertir en XMl.

J'ai essayé avec un fichier html qui contient un seul tabeau et ça à marcher mais quand le fichier html contient plusieurs tableaux les problemes commencent.

voici ou je suis arrivé:

import java.io.*;
import java.net.*;
import javax.swing.text.*;
import javax.swing.text.html.*;
import javax.swing.text.html.parser.*;

    public class mourad2 {
    	int l,g;
    	
        public static void main(String [] args) {
        Reader r;
        String spec = args[0];           
              try{  
            	  r = new FileReader(args[0]);
         
            
            HTMLEditorKit.Parser parser;
            System.out.println("About to parse " + spec);
            parser = new ParserDelegator();
           
             parser.parse(r, new HTMLParseLister2(), true);
            r.close();
        }
            catch (Exception e) {
            System.err.println("Error: " + e);
            e.printStackTrace(System.err);
        }
            
    }
}

class HTMLParseLister2 extends HTMLEditorKit.ParserCallback
    {
    int indentSize = 0;
    int z=1,y=0;
    int td=1,tr=0;
        public void handleStartTag(HTML.Tag t, MutableAttributeSet a, int pos) {
        	
        if(t.toString().equals("table") ){     	             
        	              System.out.print("\n\" );
}
if(t.toString().equals(\"tr\") ){
System.out.println();
tr++;}
if(t.toString().equals(\"td\")){td++;

}
// if(t.toString().equals(\"td\") )System.out.println(\"td= \"+td++);
}
public void handleText(char[] data, int pos) {
System.out.print(data);

System.out.print(\" \");
}
public void handleEndTag(HTML.Tag t, int pos) {
if(t.toString().equals(\"table\")){
System.out.print(\"\nligne= \"+tr);
System.out.println(\" colonne= \"+td/tr);
tr=0;
        System.out.println("
" ); 
         td=0;
        }
        }     
}



quelqu'un pourra t-il m'aider?

ça fait 21 jours que je travaille dessous et j'ai pas trouvé la solution.

J'ai posté mon probleme dans plusieurs forum et personne m'a repondu; j'espere que vous avez la reponse.

Merci d'avance.
0
Rejoignez-nous