package com.myapp.webapp.util; import java.io.FileNotFoundException; import java.io.IOException; import java.util.LinkedList; import java.util.List; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.struts.upload.FormFile; import org.apache.commons.lang.StringUtils; /** * Clase base que permite leer un fichero de excel desde java utilizando * tecnologia Jakarta - POI *

* View Source *

* * @author Cesar A. Mata de Avila * */ public class ReadExcel { /** * Este método es el encargado de leer desde el fichero de Excel la * información procesarla y devolverá en una lista de lasta para luego ser * setteada en los objetos de negocios correspondiente y su posterior * persistencia en la base de Datos * * @param file * el fichero excel a procesar * @param titles * una lista que contiene los títulos en formato String de la * columnas que se desea leer en el fichero de Excel * @param sheetName * nombre de la hoja que se desea procesar en el fichero excel * @return List una lista de lista con los datos leidos del fichero * Excel * @throws FileNotFoundException * esta exception es lanzada cuando el fichero enviado al * procedimiento no existe o no corresponde a un fichero de tipo * Excel * @throws IOException */ public static List ProcessExcelFile(FormFile file, List titles, String sheetName) throws FileNotFoundException, IOException { List headers = titles; List listObject = new LinkedList(); try { HSSFWorkbook workbook = new HSSFWorkbook(file.getInputStream()); HSSFSheet sheet = workbook.getSheet(sheetName.trim()); HSSFRow row = sheet.getRow(3); for (int i = 0; i < headers.size(); i++) { for (int j = 0; j <= row.getLastCellNum(); j++) { HSSFCell cell = row.getCell((short) j); int numFilas = sheet.getLastRowNum(); if (cell != null) if (StringUtils.equalsIgnoreCase(cell .getStringCellValue(), headers.get(i) .toString())) { List list = new LinkedList(); for (int k = 4; k <= numFilas; k++) { HSSFRow rowData = sheet.getRow(k); HSSFCell rows = null; if (rowData != null) { rows = rowData.getCell((short) j); } if (rows != null) { switch (rows.getCellType()) { case HSSFCell.CELL_TYPE_BOOLEAN: list.add(Boolean.valueOf(rows .getBooleanCellValue())); break; case HSSFCell.CELL_TYPE_NUMERIC: list.add(Double.valueOf(rows .getNumericCellValue())); break; case HSSFCell.CELL_TYPE_STRING: list.add(rows.getStringCellValue()); break; default: list.add(""); break; } } else { list.add(""); if(j==0){ numFilas = k; list.remove(list.size()-1); } } } listObject.add(list); } } } // return listObject; } catch (Exception e) { // TODO: handle exception } return listObject; } }