I am developing a java application that allows me to read files .xls
and .xlsx
. I managed to implement the reading extension .xls
with the Apache POI 3.13 library using HSSFWorkbook
and I know that I need XSSFWorkbook
to read .xlsx
.
My question is if and how I can make the app read both extensions.
Attached part of the code with which I read a file in .xls
HSSFWorkbook workBook = new HSSFWorkbook (fileSystem);
HSSFSheet sheet = workBook.getSheetAt (0);
int totalRows = sheet.getPhysicalNumberOfRows();
System.out.println("Filas totales: "+totalRows);
if (totalRows <= 4){
JOptionPane.showMessageDialog(null,
"El archivo debe contener al menos 1 artículo.", //Mensaje
"Mensaje de Advertencia", //Título
JOptionPane.WARNING_MESSAGE);
}
Iterator<?> rows = sheet.rowIterator ();
ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>();
while (rows.hasNext ())
{
HSSFRow row = (HSSFRow) rows.next();
int rowNumber = row.getRowNum ();
// muestra el número de fila
System.out.println ("No. Fila: " + rowNumber);
// get a row, iterate through cells.
Iterator<?> cells = row.cellIterator ();
ArrayList<String> rowData = new ArrayList<String>();
while (cells.hasNext ())
{
HSSFCell cell = (HSSFCell) cells.next ();
switch (cell.getCellType ())
{
case HSSFCell.CELL_TYPE_NUMERIC :
{
// NUMERIC CELL TYPE
System.out.println ("Numerico: " + cell.getNumericCellValue ());
rowData.add(cell.getNumericCellValue () + "");
break;
}
case HSSFCell.CELL_TYPE_BLANK :
{
// NUMERIC CELL TYPE
System.out.println ("Campo en Blanco" + cell.getErrorCellValue ());
rowData.add(cell.getErrorCellValue () + "");
break;
}
case HSSFCell.CELL_TYPE_STRING :
{
// STRING CELL TYPE
HSSFRichTextString richTextString = cell.getRichStringCellValue ();
System.out.println ("String: " + richTextString.getString ());
rowData.add(richTextString.getString ());
break;
}
default:
{
// types other than String and Numeric.
System.out.println ("Tipo de dato no soportado.");
break;
}
} // end switch
} // end while
data.add(rowData);
You can read both types of files using POI. Here is a basic example to open excel files (xls or xlsx) using the generic interfaces provided by POI:
Using the interfaces
Workbook
,Sheet
,Row
andCell
the source doesn't matter. Also, these interfaces have methods similar to those you find for working with HSSF, so you get the hang of it faster.Hello, maybe your question has already been answered but I would do it in a single method as follows: this method reads and writes in jtable.