How to export data from an XML to excel using java?

Good afternoon,

I am trying to extract the contents of an XML to write to an excel, they will have some reference to perform it.

 0
Author: rayo, 2016-06-03

1 answers

A simple example of how to read an XML, navigate its nodes and read its data (simplified example of http://www.tutorialspoint.com/java_xml/java_dom_parse_document.htm):

Student Content.xml:

<?xml version="1.0"?>
<clase>
   <alumno num="11">
      <nombre>Luis</nombre>
      <calificacion>85</calificacion>
   </alumno>
   <alumno num="15">
      <nombre>Jaime</nombre>
      <calificacion>70</calificacion>
   </alumno>
   <alumno num="17">
      <nombre>Pedro</nombre>
      <calificacion>90</calificacion>
   </alumno>
</clase>

Code:

import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.*;

....    

File inputFile = new File("alumnos.xml"); //Ruta al archivo XML

DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();

//Ejemplo de obtener el nombre de una etiqueta
System.out.println("Elemento raiz :" + doc.getDocumentElement().getNodeName());
//Se buscan todos los nodos con la etiqueta "alumno"
NodeList nList = doc.getElementsByTagName("alumno");

//Se itera por cada nodo para extraer los datos
for (int i = 0; i < nList.getLength(); i++) {
    System.out.println("----------------------------");
    Node nNode = nList.item(i);
    if (nNode.getNodeType() == Node.ELEMENT_NODE) {
        Element eElement = (Element) nNode;
        //Obtener el valor de un atributo:
        System.out.println("Estudiante número:"
                + eElement.getAttribute("num"));
        //Obtener el contenido de una etiqueta
        System.out.println("Nombre : "
                + eElement
                .getElementsByTagName("nombre")
                .item(0)
                .getTextContent());
        System.out.println("Calificacion : "
                + eElement
                .getElementsByTagName("calificacion")
                .item(0)
                .getTextContent());
    }
}

Result:

Elemento raiz :clase
----------------------------
Estudiante número:11
Nombre : Luis
Calificacion : 85
----------------------------
Estudiante número:15
Nombre : Jaime
Calificacion : 70
----------------------------
Estudiante número:17
Nombre : Pedro
Calificacion : 90

You can try this example without the need for external libraries, but it has low performance, if you need better performance there are other libraries that you can use .

Since have the data to assemble the Excel I recommend Apache POI, for this you need to get the library. If you have Maven or a dependency manager you can add it to your pom.xml:

<!--
  (Te puedes meter a esta liga para descargarlo manualmente) 
  http://mvnrepository.com/artifact/org.apache.poi/poi 
 -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.14</version>
</dependency>

Otherwise you can download it from the official website: https://poi.apache.org/download.html

To create a file:

Workbook wb = new HSSFWorkbook();
CreationHelper createHelper = wb.getCreationHelper();
Sheet sheet = wb.createSheet("new sheet");

// Crear renglon y ponerle celdas.
Row row = sheet.createRow((short)0);
// Crear celda y ponerle un valor
Cell cell = row.createCell(0);
cell.setCellValue(1);

// Tambien se pueden crear en una sola linea
row.createCell(1).setCellValue(1.2);
row.createCell(2).setCellValue(createHelper.createRichTextString("Esto es un String"));

// Escribir el archivo
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();

In the "write the file" part you will write it directly to the folder where the program is running, you have not told us if your file you want to serve it that way or if you need to send it to a browser. If you have specific doubts you can ask again. Greeting.

 2
Author: Juan Algaba, 2016-06-06 02:17:14