Hola amigos javeros, bueno hace algunos días ayude a un amigo para poder leer archivos de EXCEL 2007, aunque ya contaba con un código que leia los archivos .xls los archivos Excel XLSX se leen de manera diferente, primaro para realizar esto es necesario contar con las siguientes librerías.
- • poi-3.7-20101029
- • poi-ooxml-3.7-20101029
- • poi-ooxml-schemas-3.7-20101029
- • poi-scratchpad-3.7-20101029
- • xmlbeans-2.3.0
- • dom4j-1.6.1
Una vez que contamos con esta información es momento de pasar al código a continuación les dejo el código.
import java.io.File;
import java.io.FileInputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Prueba {
public Prueba(File fileName) throws ParseException{
List cellDataList = new ArrayList();
try{
FileInputStream fileInputStream = new FileInputStream( fileName);
XSSFWorkbook workBook = new XSSFWorkbook(fileInputStream);
XSSFSheet hssfSheet = workBook.getSheetAt(0);
Iterator rowIterator = hssfSheet.rowIterator();
while0 (rowIterator.hasNext()){
XSSFRow hssfRow = (XSSFRow) rowIterator.next();
Iterator iterator = hssfRow.cellIterator();
List cellTempList = new ArrayList();
while (iterator.hasNext()){
XSSFCell hssfCell = (XSSFCell) iterator.next();
cellTempList.add(hssfCell);
}
cellDataList.add(cellTempList);
}
}catch (Exception e)
{e.printStackTrace();}
Leer(cellDataList);
}
private void Leer(List cellDataList){
for (int i = 0; i < cellDataList.size(); i++){
List cellTempList = (List) cellDataList.get(i);
for (int j = 0; j < cellTempList.size(); j++){
XSSFCell hssfCell = (XSSFCell) cellTempList.get(j);
String stringCellValue = hssfCell.toString();
System.out.print(stringCellValue+" ");
}
System.out.println();
}
}
public static void main(String[] args) throws ParseException{
File f=new File("C:/prueba.xlsx");
if(f.exists()){
Prueba pb=new Prueba(f);
}
}
}
Nota: este código solo funciona con archivos con extensión .XLSX para los archivos con extensión .xls se utiliza otro código que posteo uno de mis compañeros, saludos.











Ver una entrada al azar
Muchas gracias, Excelente trabajo. Ojala pudieran subir tambien el otro codigo para .xls.
ResponderEliminarDe nada amigo, sera el próximo saludos
ResponderEliminarhola muy buen tutorial, yo utilizo la versión anterior que se llama jexcel-api y creo que le sirve a anonimo porque solo puedes leer archivos xls te dejo la liga por si aún la necesitan..
ResponderEliminaroops creo que no subi el tutorial pero si necesitan como cuentenme y les paso el código.
Saludos
http://robertoleon.com.mx/blog/
Gracias por la info ahí nos seguimos @JaverosAnonimos
ResponderEliminarGracias, man... probando, esto es justo lo q necesito y no tenía ni idea de como empezar, ya encontré el código para xls, solo me faltaba para el "nuevo formato" de mocosoft...
ResponderEliminarNo me da :( aparece Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
ResponderEliminarHola!
ResponderEliminarEl código funciona, tal vez has cambiado algo no puedes dar mas detalle para poder ayudarte?
estoy intentando leer un archivo de excel de 1 millon de registros pero me tira ese error el codigo que tengo es
ResponderEliminarpackage com.myjeeva.poi.demo;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.util.IOUtils;
import com.myjeeva.poi.ExcelReader;
import com.myjeeva.poi.ExcelWorkSheetHandler;
import com.myjeeva.poi.demo.vo.PersonVO;
import java.util.Iterator;
/**
* Demonstration of Generic Excel File (XLSX) Reading using Apache POI
*
* @author Jeevanandam Madanagopal
*/
public class Excel2JavaDemo {
private static final Log LOG = LogFactory.getLog(Excel2JavaDemo.class);
/**
* @param args
* @throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
String SAMPLE_PERSON_DATA_FILE_PATH = "src/main/resources/Sample-Person-Data.xlsx";
/*
* Input File initialize
*/
File file = new File(SAMPLE_PERSON_DATA_FILE_PATH);
InputStream inputStream = new FileInputStream(file);
/*
* Excel Cell Mapping
*/
Map cellMapping = new HashMap();
cellMapping.put("HEADER", "Person Id,Name,Height,Email Address,DOB,Salary,Mayority");
cellMapping.put("A", "personId");
cellMapping.put("B", "name");
cellMapping.put("C", "height");
cellMapping.put("D", "emailId");
cellMapping.put("E", "dob");
cellMapping.put("F", "salary");
cellMapping.put("G", "mayority");
// The package open is instantaneous, as it should be.
OPCPackage pkg = null;
try {
ExcelWorkSheetHandler workSheetHandler = new ExcelWorkSheetHandler(
PersonVO.class, cellMapping);
System.out.println(workSheetHandler);
pkg = OPCPackage.open(inputStream);
ExcelReader excelReader = new ExcelReader(pkg, workSheetHandler);
excelReader.process();
if (workSheetHandler.getValueList().isEmpty()) {
// No data present
LOG.error("sHandler.getValueList() is empty; it means something went wrong parsing excel file");
} else {
LOG.info(workSheetHandler.getValueList().size()
+ " no. of records read from given excel worksheet successfully.");
/*
* Displaying data ead from Excel file
*/
displayPersonList(workSheetHandler.getValueList());
}
} catch (RuntimeException are) {
LOG.error(are.getMessage(), are.getCause());
} catch (InvalidFormatException ife) {
LOG.error(ife.getMessage(), ife.getCause());
} catch (IOException ioe) {
LOG.error(ioe.getMessage(), ioe.getCause());
} finally {
IOUtils.closeQuietly(inputStream);
try {
if (null != pkg) {
pkg.close();
}
} catch (IOException e) {
// just ignore IO exception
}
}
}
private static void displayPersonList(List persons) {
ResponderEliminarSystem.out.println("Id\tName\tHeight\tEmail Address\t\tDOB\t\tSalary\t\tMayority");
System.out.println("--\t----\t------\t-------------\t\t---\t\t------\t\t------");
int NumRegistros=0;
int NumEmpleadosSalMay=0;
int SalMay;
int Comparacion=30000;
int Salary=0;
for (PersonVO p : persons) {
System.out.println(String.format("%s\t%s\t%s\t%s\t%s\t%s\t%s",
p.getPersonId(), p.getName(), p.getHeight(),
p.getEmailId(), p.getDob(), p.getSalary(),p.getMayority()));
NumRegistros++;
SalMay=Integer.parseInt(p.getSalary());
if(SalMay>=Comparacion){
NumEmpleadosSalMay++;
}
Salary = Salary + Integer.parseInt(p.getSalary());
}
System.out.println("Numero de registros: "+NumRegistros);
System.out.println("Numero de empleados con salarios mayores: "+NumEmpleadosSalMay);
System.out.println("Total de nomina a desembolsar: "+String.format("%s",String.valueOf(Salary)));
System.gc();
}
}
Sirve pero para excel con pocos registros
ResponderEliminar