I have already solved the export of an Excel sheet to a Jtable in Java. The problem arises in Excel cells that have been calculated using formula. In these cases, the Jtable does not interpret the format and the export is interrupted. Do you know any solution about it? This is the code that I use.
public class importExcel {
Workbook wb;
public String Importar (File archivo, JTable tabla){
String respuesta="No se ha podido importar el fichero Excel.";
DefaultTableModel modeloT=new DefaultTableModel();
tabla.setModel(modeloT);
try{
wb=WorkbookFactory.create(new FileInputStream(archivo));
Sheet hoja=wb.getSheetAt(0);
Iterator filaIterator=hoja.rowIterator();
int indiceFila=-1;
while(filaIterator.hasNext()){
indiceFila++;
Row fila=(Row)filaIterator.next();
Iterator columnaIterator=fila.cellIterator();
Object[] listaColumna= new Object[20];//Averiguar porque es 5
int indiceColumna=-1;
while(columnaIterator.hasNext()){
indiceColumna++;
Cell celda=(Cell) columnaIterator.next();
if(indiceFila==0){
modeloT.addColumn(celda.getStringCellValue());
}else{
if(celda!=null){
switch(celda.getCellType()){
case Cell.CELL_TYPE_NUMERIC:
if( HSSFDateUtil.isCellDateFormatted(celda) ){
CellStyle cellStyle = wb.createCellStyle();
CreationHelper createHelper = wb.getCreationHelper();
cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("dd/mm/yyyy"));
//Aqui se puede cortar el bucle con una condición sobre la fecha o cualquier otra cosa
celda.setCellValue(celda.getDateCellValue());
celda.setCellStyle(cellStyle);
listaColumna[indiceColumna]=celda.getDateCellValue();
}else{
listaColumna[indiceColumna]=celda.getNumericCellValue();
}break;
case Cell.CELL_TYPE_STRING:
listaColumna[indiceColumna]=celda.getStringCellValue();
break;
case Cell.CELL_TYPE_BOOLEAN:
listaColumna[indiceColumna]=celda.getBooleanCellValue();
break;
default:
listaColumna[indiceColumna]=celda.getDateCellValue();
break;
}
}
}
}
if(indiceFila!=0){
modeloT.addRow(listaColumna);
}
}
respuesta="Exportación realizada con éxito";
}catch(Exception e){
}
return respuesta;
}