Este post lo puedes ver también en http://www.javamexico.org/blogs/sr_negativo/aprendiendo_java_en_quotserioquot_008
Es una librería para el tratamiento de archivos de excel y word desde programas Java.
CreaExcel.java
package org.programacion.task04; import java.io.FileOutputStream; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFRichTextString; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; public class CreaExcel { public static void main(String ... args)throws Exception{ /*libro*/ HSSFWorkbook miLibro= new HSSFWorkbook(); /*hoja*/ HSSFSheet hoja = miLibro.createSheet(); /*fila*/ HSSFRow fila = hoja.createRow(0); /*celda*/ HSSFCell celda = fila.createCell((short) 0); /*contenido celda*/ HSSFRichTextString texto = new HSSFRichTextString("Un simple mensaje"); celda.setCellValue(texto); try{ FileOutputStream archivo = new FileOutputStream("C:/Users/usuario/Documents/Programas/Ejemplos/archivoExcel.xls"); miLibro.write(archivo); System.out.println("... archivo excel creado"); archivo.close(); }catch(Exception ex){ System.err.println("error: ["+ex+"] causa: ["+ex.getCause()+"]"); } } }
El ejemplo viene de http://chuwiki.chuidiang.org/index.php?title=Crear_archivo_Excel_desde_Java_con_POI
Debe generar un archivo de Excel
Y debe mostrar el mensaje: "Un simple mensaje"
Ahora se me ocurre leer el contenido del archivo generado.
LeerExcel.java
package org.programacion.task04; import java.io.FileInputStream; 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.poi.poifs.filesystem.POIFSFileSystem; public class LeerExcel{ public static void main(String ... args)throws Exception{ try{ //Se abre el fichero Excel POIFSFileSystem fs = new POIFSFileSystem( new FileInputStream("C:/Users/usuario/Documents/Programas/Ejemplos/archivoExcel.xls")); //Se obtiene el libro Excel HSSFWorkbook wb = new HSSFWorkbook(fs); //Se obtiene la primera hoja HSSFSheet sheet = wb.getSheetAt(0); //Se obtiene la primera fila de la hoja HSSFRow row = sheet.getRow(0); //leer celda 0 HSSFCell cell = row.getCell((short)0); System.out.println("[Lectura]"); System.out.println("el mensaje dice: ["+cell.getStringCellValue()+"]"); }catch(Exception ex){ System.err.println("error: ["+ex+"] causa: ["+ex.getCause()+"]"); } } }
Ahora un ejemplo con Word.Para esta aplicación se va usar además la librería log4j.
log.properties
# root logger to DEBUG, and its only appender to A1 log4j.rootLogger=DEBUG, A1 # A1 se asigna a ConsoleAppender log4j.appender.A1=org.apache.log4j.ConsoleAppender # A1 usa PatternLayout. log4j.appender.A1.layout=org.apache.log4j.PatternLayout log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
Esta es una configuración básica, nos permite hacer una "depuración sencilla". Este ejemplo viene de Adictos al trabajo: Leer un documento de WORD usando la librería POI de jakarta.
AnalizadorWord.java
package org.programas.task01; import java.io.FileInputStream; import org.apache.log4j.Logger; import org.apache.log4j.BasicConfigurator; import org.apache.poi.poifs.eventfilesystem.POIFSReader; public class AnalizadorWord { private int numeroCaracteres; private int numeroPalabras; private int numeroPaginas; private String titulo; private String autor; private String comentarios; private String texto; private String nombreFichero; public AnalizadorWord(String nombreFichero) { this.nombreFichero = this.nombreFichero; } static Logger log = Logger.getLogger(AnalizadorWord.class.getName()); public static void main(String ... args){ BasicConfigurator.configure(); String filename = "C:/Users/usuario/Desktop/Documentos/Respaldo/Nueva info/ejemplo.doc"; AnalizadorWord analizador = new AnalizadorWord(filename); log.info("... iniciando aplicación"); try{ analizador.analizar(); log.info("... aplicación funcionando correctamente"); }catch(Exception ex){ log.error("error: ["+ex+"] causa: ["+ex.getCause()+"]"); } }//fin main @Override public String toString() { StringBuffer sb = new StringBuffer(""); sb.append("\n TITULO DEL DOCUMENTO:"+getTitulo()); sb.append("\n AUTOR DEL DOCUMENTO:"+getAutor()); sb.append("\n COMENTARIOS DEL DOCUMENTO:"+getComentarios()); sb.append("\n NUMERO DE CARACTERES:"+getNumeroCaracteres()); sb.append("\n NUMERO DE PALABRAS:"+getNumeroPalabras()); sb.append("\n NUMERO DE PAGINAS:"+getNumeroPaginas()); sb.append("\n ------ TEXTO --------"); sb.append("\n"); sb.append(getTexto()); sb.append("\n ------ TEXTO --------"); return sb.toString(); } public void analizar() throws Exception { POIFSReader r1 = new POIFSReader(); FileInputStream fis=null; StandardReaderListener stdReader = new StandardReaderListener(); stdReader.setDatos(this); r1.registerListener(stdReader, "\005SummaryInformation"); try { fis = new FileInputStream(this.nombreFichero); r1.read(fis); log.info("... leyendo archivo"); } catch (Exception e) { log.error("Error->" + e.toString()+" clase: "+AnalizadorWord.class.getName()); } finally { if(fis!=null) fis.close(); } } /** * @return the numeroCaracteres */ public int getNumeroCaracteres() { return numeroCaracteres; } /** * @param numeroCaracteres the numeroCaracteres to set */ public void setNumeroCaracteres(int numeroCaracteres) { this.numeroCaracteres = numeroCaracteres; } /** * @return the numeroPalabras */ public int getNumeroPalabras() { return numeroPalabras; } /** * @param numeroPalabras the numeroPalabras to set */ public void setNumeroPalabras(int numeroPalabras) { this.numeroPalabras = numeroPalabras; } /** * @return the numeroPaginas */ public int getNumeroPaginas() { return numeroPaginas; } /** * @param numeroPaginas the numeroPaginas to set */ public void setNumeroPaginas(int numeroPaginas) { this.numeroPaginas = numeroPaginas; } /** * @return the titulo */ public String getTitulo() { return titulo; } /** * @param titulo the titulo to set */ public void setTitulo(String titulo) { this.titulo = titulo; } /** * @return the autor */ public String getAutor() { return autor; } /** * @param autor the autor to set */ public void setAutor(String autor) { this.autor = autor; } /** * @return the comentarios */ public String getComentarios() { return comentarios; } /** * @param comentarios the comentarios to set */ public void setComentarios(String comentarios) { this.comentarios = comentarios; } /** * @return the texto */ public String getTexto() { return texto; } /** * @param texto the texto to set */ public void setTexto(String texto) { this.texto = texto; } /** * @return the nombreFichero */ public String getNombreFichero() { return nombreFichero; } /** * @param nombreFichero the nombreFichero to set */ public void setNombreFichero(String nombreFichero) { this.nombreFichero = nombreFichero; } }
StandardReaderListener.java
package org.programas.task01; import java.io.FileInputStream; import org.apache.poi.hpsf.PropertySetFactory; import org.apache.poi.hpsf.SummaryInformation; import org.apache.poi.hwpf.extractor.WordExtractor; import org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent; import org.apache.poi.poifs.eventfilesystem.POIFSReaderListener; import org.apache.log4j.Logger; import org.apache.log4j.BasicConfigurator; public class StandardReaderListener implements POIFSReaderListener{ static Logger log = Logger.getLogger(StandardReaderListener.class.getName()); private AnalizadorWord datos=null; public void setDatos(AnalizadorWord datos) { this.datos = datos; } @Override public void processPOIFSReaderEvent(POIFSReaderEvent event) { // Clase que almacena las características estándar de un documento. SummaryInformation si = null; try { si = (SummaryInformation)PropertySetFactory.create(event.getStream()); } catch (Exception ex) { throw new RuntimeException ("Property set stream \"" + event.getPath() + event.getName() + "\": " + ex); } /* Recogemos los datos que nos interesan y los almacenamos en la clase AnalizadorWord.*/ datos.setTitulo(si.getTitle()); datos.setAutor(si.getAuthor()); datos.setComentarios(si.getComments()); datos.setNumeroCaracteres(si.getCharCount()); datos.setNumeroPalabras(si.getWordCount()); datos.setNumeroPaginas(si.getPageCount()); /* Usamos la clase WordExtractor para obtener el texto del documento */ WordExtractor we = null; try { FileInputStream fis = new FileInputStream(datos.getNombreFichero()); we = new WordExtractor(fis); fis.close(); } catch (Exception e1) { log.error("Aqui parece el error"+e1.toString()+" clase: "+StandardReaderListener.class.getName()); } datos.setTexto(we.getText()); } }
Enlaces:
https://poi.apache.org/






Gracias por la informacion, la voy a probar ya que soy nuevo en esto del tratamiento de documentos, saludos :)
ResponderEliminar