I would like to know how I can convert data read by a Java class that allows me to read documents in Excel .xls
, .xlsx
and .xlsm
through the library POI
to a structure XML
, it is worth mentioning that the class reads the files and shows me the results in the console.
Now, how could I generate an XML structure from that data? Do I need a specific library or what can I do?
I attach the code that reads the data from Excel:
public class ExcelReader{
public void displayFromExcel() throws FileNotFoundException, IOException, EncryptedDocumentException, InvalidFormatException
{
File archivoExcel = new File("C:\\Users\\1\\Desktop\\archivo.xlsx"); //ruta del archivo xls o xlsx
Workbook libroExcel = WorkbookFactory.create(new FileInputStream(archivoExcel)); //crear un libro excel
Sheet hojaActual = libroExcel.getSheetAt(0); //acceder a la primera hoja
Row filaActual = hojaActual.getRow(0); //acceder a la primera fila en la hoja
Cell celdaActual = filaActual.getCell(0); //acceder a la primera celda en la fila
Iterator<Row> rows = hojaActual.rowIterator();
while (rows.hasNext())
{
Row row = (Row) rows.next();
int rowNumber = row.getRowNum();
// muestra el número de fila
System.out.println ("No. Fila: " + rowNumber);
filaActual= rows.next();
Iterator<Cell> cells = filaActual.cellIterator();
while (cells.hasNext())
{
celdaActual= cells.next();
cells.remove();
if (celdaActual.getCellType() == Cell.CELL_TYPE_STRING)
{
System.out.println("String: "+celdaActual.getStringCellValue()+" ");
}
else if(celdaActual.getCellType() == Cell.CELL_TYPE_NUMERIC)
{
System.out.println("Int: "+celdaActual.getNumericCellValue()+" ");
}
else
{
//U Can Handel Boolean, Formula, Errors
}
}
System.out.println();
}
}
public static void main (String[] args) throws EncryptedDocumentException, FileNotFoundException, InvalidFormatException, IOException
{
MyExp exp = new MyExp();
exp.displayFromExcel();
}
}
Always remember that in programming (and in the software world in general) problems can be simplified using divide and conquer . So, your problem can be divided into the following parts (each one easier if seen as a point problem):
It seems that you should only continue with parts 2 and 3. Since we don't know what the data in your Excel file looks like or how you want it to be structured, part 2 will depend on your needs. For part 3, you can use JAXB which is native to Java or some external library. Personally, I recommend the use of XStream with
StaxDriver
(Disclaimer 1 : I am not associated in any way with the XStream project or the development team, I am just a happy user of the product and its results).1 Legal Notice seems to be a good Spanish translation of Disclaimer