0

I'm trying to export a JTable to a file usable by Microsoft Excel.

Originally, I wrote the data to a text file and set the extension as ".xls"

Of course, this was unprofessional, and Excel went on to complain about the format being out of whack. Rightly so.

Anyway, now I'm trying to export it to an XML table, that way I can open it with Excel. However, when I try to export it with XMLEncoder, exceptions are printed, and when opened in Excel, it does not look or work right. Rather than having the data from the tables, the table contains data about the objects and classes.

Here's my code:

public static void saveToXML(JTable table, File location, String name) throws Exception{

    XMLEncoder encoder;
    File file = new File(location.getAbsolutePath() + "/" + name + ".xml");

    encoder = new XMLEncoder(new FileOutputStream(file));
    encoder.writeObject(table);
    encoder.close();

}

The exceptions that are printed are as follows:

 java.lang.InstantiationException: fbla.evaluation.window.MainWindow$2
Continuing ...
java.lang.RuntimeException: failed to evaluate: <unbound>=Class.new();
Continuing ...
java.lang.InstantiationException: javax.swing.plaf.basic.BasicTableHeaderUI$MouseInputHandler
Continuing ...
java.lang.Exception: XMLEncoder: discarding statement JTableHeader.removeMouseMotionListener(BasicTableHeaderUI$MouseInputHandler);
Continuing ...
java.lang.InstantiationException: fbla.evaluation.window.MainWindow$38
Continuing ...
java.lang.Exception: XMLEncoder: discarding statement JTable.addMouseListener(MainWindow$38);
Continuing ...
java.lang.InstantiationException: javax.swing.plaf.basic.BasicTableUI$Handler
Continuing ...
java.lang.Exception: XMLEncoder: discarding statement JTable.removeMouseMotionListener(BasicTableUI$Handler);
Continuing ...

Any help and insight is greatly appreciated. It's probably also worth mentioning that the tables Model is a custom one.

kleopatra
  • 51,061
  • 28
  • 99
  • 211
Anonymous
  • 696
  • 8
  • 21

3 Answers3

1

You can export the TableModel to the clipboard as shown here and here.

Addendum: The table's Model is a custom one.

As long as your table's model is a TableModel, you can extract the data as shown here.

If Office Open XML (OOXML) format is acceptable, you may be able to use Apache POI to create the file.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • Thank you, but not exactly the answer I'm looking for. I'd like to have the XMLEncoder work. – Anonymous Apr 15 '13 at 03:23
  • You can read the generated XML with `XMLDecoder`, for [example](http://javaprogramming.language-tutorial.com/2012/10/convert-java-object-to-xml-and-convert.html), but Excel cannot; more [here](http://stackoverflow.com/a/5898529/230513). – trashgod Apr 15 '13 at 04:00
  • Is there a way to export a JTable using Java so that Excel CAN read it? It's a rather important function to put in, but I'd rather not use an API due to licensing issues. – Anonymous Apr 16 '13 at 02:06
  • You can write a CSV file while [looping through the model](http://stackoverflow.com/a/15731782/230513). Seek legal counsel on licensing. – trashgod Apr 16 '13 at 03:58
0

this is the code I write, I use the DOMParse. In my case, the JTable I get the info from has always the same numbers of columns so I just sitch rows with the FOR.

In short the basic steps one has to take in order to create an XML File withe a DOM Parser are:

  • Create a DocumentBuilder instance.
  • Create a DocumentBuilder instance.
  • Create a DocumentBuilder instance.
  • Create a Document from the above DocumentBuilder.
  • Create the elements you want using the Element class and its appendChild method.
  • Create the elements you want using the Element class and its appendChild method.
  • Create a new Transformer instance and a new DOMSource instance.
  • Create a new StreamResult to the output stream you want to use.
  • Use transform method to write the DOM object to the output stream you want.
    static String getPath = "";

    public void setPath(String path) {
        getPath = getPath.concat(path);
        getPath = getPath.concat(".xml");
    }

    
    public void importToXML(JTable tabla) {
        try {
            DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder();
            Document document = documentBuilder.newDocument();

            Element root = document.createElement("calculos");
            document.appendChild(root);
            
            for (int i = 0; i < tabla.getRowCount(); i++) {
                Element articulo = document.createElement("articulo");
                root.appendChild(articulo);

                Element tipo = document.createElement("name1");
                tipo.appendChild(document.createTextNode("" + tabla.getValueAt(i, 0)));
                articulo.appendChild(tipo);

                Element unidades = document.createElement("name2");
                unidades.appendChild(document.createTextNode("" + tabla.getValueAt(i, 1)));
                articulo.appendChild(unidades);

                Element costounitarioDLS = document.createElement("name3");
                costounitarioDLS.appendChild(document.createTextNode("" + tabla.getValueAt(i, 2)));
                articulo.appendChild(costounitarioDLS);

                Element costounitarioPesos = document.createElement("name4");
                costounitarioPesos.appendChild(document.createTextNode("" + tabla.getValueAt(i, 3)));
                articulo.appendChild(costounitarioPesos);

                Element porcentajeIGI = document.createElement("name5");
                porcentajeIGI.appendChild(document.createTextNode("" + tabla.getValueAt(i, 4)));
                articulo.appendChild(porcentajeIGI);

                Element montoIGI = document.createElement("name6");
                montoIGI.appendChild(document.createTextNode("" + tabla.getValueAt(i, 5)));
                articulo.appendChild(montoIGI);
            }

            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource domSource = new DOMSource(document);

            StreamResult streamResult = new StreamResult(new File(getPath));
            transformer.transform(domSource, streamResult);
        } catch (ParserConfigurationException | TransformerException pce) {
            JOptionPane.showMessageDialog(null, "Error: " + pce.toString());
        }
    }

I just get this code to work, so it can be optimized. Hope this helps anyone searching for an aswe.

-1

Maybe you should try this:Java Swing -Export JTable To Excel File

void ExportToExel(JTable table, File file) {

    try {

        WritableWorkbook workbook1 = Workbook.createWorkbook(file);
        WritableSheet sheet1 = workbook1.createSheet("First Sheet", 0); 
        TableModel model = table.getModel();

        for (int i = 0; i < model.getColumnCount(); i++) {
            Label column = new Label(i, 0, model.getColumnName(i));
            sheet1.addCell(column);
        }
        int j = 0;
        for (int i = 0; i < model.getRowCount(); i++) {
            for (j = 0; j < model.getColumnCount(); j++) {
                Label row = new Label(j, i + 1, 
                        model.getValueAt(i, j).toString());
                sheet1.addCell(row);
            }
        }
        workbook1.write();
        workbook1.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
alex
  • 11
  • 3