简体   繁体   English

导出 JTable 到 XML 文件

[英]Exporting JTable to XML File

I'm trying to export a JTable to a file usable by Microsoft Excel.我正在尝试将 JTable 导出到 Microsoft Excel 可用的文件。

Originally, I wrote the data to a text file and set the extension as ".xls"最初,我将数据写入文本文件并将扩展名设置为“.xls”

Of course, this was unprofessional, and Excel went on to complain about the format being out of whack.当然,这是不专业的,Excel 继续抱怨格式不对劲。 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.无论如何,现在我正在尝试将它导出到 XML 表,这样我就可以用 Excel 打开它。但是,当我尝试用 XMLEncoder 导出它时,会打印异常,并且在 Excel 中打开时,它看起来或工作正常。 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.可能还值得一提的是,表 Model 是一个自定义表。

You can export the TableModel to the clipboard as shown here and here . 您可以将TableModel导出到剪贴板,如此此处所示。

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 . 只要你的表的模型是一个TableModel ,可以提取数据如图所示这里

If Office Open XML (OOXML) format is acceptable, you may be able to use Apache POI to create the file. 如果可以使用Office Open XML(OOXML)格式,则可以使用Apache POI创建文件。

this is the code I write, I use the DOMParse.这是我写的代码,我使用 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.在我的例子中,我从中获取信息的 JTable 始终具有相同的列数,因此我只需使用 FOR 来分隔行。

In short the basic steps one has to take in order to create an XML File withe a DOM Parser are:简而言之,使用 DOM 解析器创建 XML 文件必须采取的基本步骤是:

  • Create a DocumentBuilder instance.创建一个 DocumentBuilder 实例。
  • Create a DocumentBuilder instance.创建一个 DocumentBuilder 实例。
  • Create a DocumentBuilder instance.创建一个 DocumentBuilder 实例。
  • Create a Document from the above DocumentBuilder.从上面的 DocumentBuilder 创建一个文档。
  • Create the elements you want using the Element class and its appendChild method.使用 Element class 及其 appendChild 方法创建所需的元素。
  • Create the elements you want using the Element class and its appendChild method.使用 Element class 及其 appendChild 方法创建所需的元素。
  • Create a new Transformer instance and a new DOMSource instance.创建一个新的 Transformer 实例和一个新的 DOMSource 实例。
  • Create a new StreamResult to the output stream you want to use.新建一个StreamResult到你要使用的output stream。
  • Use transform method to write the DOM object to the output stream you want.使用transform方法将DOM object写入你想要的output stream。
    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.希望这可以帮助任何正在寻找 aswe 的人。

Maybe you should try this: Java Swing -Export JTable To Excel File 也许您应该尝试以下操作: Java Swing-将JTable导出到Excel文件

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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM