Ir al contenido principal

Java export Excel JExcel - POI

Escribir un Excel con JExcel

Liberias que utiliza
import java.io.File;
import java.util.Date;
import jxl.*;
import jxl.write.*;

//Declaro la variable
WritableWorkbook workbook = Workbook.createWorkbook(new File("output.xls"));

//Creo una hoja en el workbook generado
WritableSheet sheet = workbook.createSheet("First Sheet", 0);

//Ahora solo queda agregar información a las celdas.

Label label = new Label(0, 2, "A label record");
sheet.addCell(label);

Number number = new Number(3, 4, 3.1459);
sheet.addCell(number);

// Luego que todas las celdas estan cargadas guardamos el workbook
workbook.write();
workbook.close();

Formateo de datos


Formato en celdas

WritableFont arial10font = new WritableFont(WritableFont.ARIAL, 10);
WritableCellFormat arial10format = new WritableCellFormat (arial10font);

Label label2 = new Label(1,0, "Arial 10 point label", arial10format);
sheet.addCell(label2);

Formatear numeros

WritableCellFormat integerFormat = new WritableCellFormat (NumberFormats.INTEGER);
Number number2 = new Number(0, 4, 3.141519, integerFormat);
sheet.addCell(number2);

WritableCellFormat floatFormat = new WritableCellFormat (NumberFormats.FLOAT);
Number number3 = new Number(1, 4, 3.141519, floatFormat);
sheet.addCell(number3);

Agregar mascaras

NumberFormat fivedps = new NumberFormat("#.#####");
WritableCellFormat fivedpsFormat = new WritableCellFormat(fivedps);
Number number4 = new Number(2, 4, 3.141519, fivedpsFormat);
sheet.addCell(number4);

Formateamos fechas

Date now = Calendar.getInstance().getTime();
DateFormat customDateFormat = new DateFormat ("dd MMM yyyy hh:mm:ss");
WritableCellFormat dateFormat = new WritableCellFormat (customDateFormat);
DateTime dateCell = new DateTime(0, 6, now, dateFormat);
sheet.addCell(dateCell);


- Exportar Excel con POI

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.hssf.usermodel.
HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
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 DemoPOI {

public static void main(String[] args){
escribirExcel();
// leerExcel();
System.out.println("Ejemplo Finalizado.");
}

public static void escribirExcel(){

try{
/*
//Se crea el libro Excel
HSSFWorkbook wb = new HSSFWorkbook();
//Se crea una nueva hoja dentro del libro
HSSFSheet sheet = wb.createSheet("HojaEjemplo");
//Se crea una fila dentro de la hoja
HSSFRow row = sheet.createRow((short)0);
//Creamos celdas de varios tipos
row.createCell((short)0).setCellValue(1);
row.createCell((short)1).setCellValue(1.2);
row.createCell((short)2).setCellValue("ejemplo");
row.createCell((short)3).setCellValue(true);
//Creamos una celda de tipo fecha y la mostramos
//indicando un patrón de formato
HSSFCellStyle cellStyle = wb.createCellStyle();
cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("d/m/yy h:mm"));
HSSFCell cell = row.createCell((short)4);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);
//Escribimos los resultados a un fichero Excel
FileOutputStream fileOut = new FileOutputStream("C:/ejemplo.xls");
wb.write(fileOut);
fileOut.close();
*/

HSSFWorkbook objLibro = new HSSFWorkbook();

// Creo la hoja
HSSFSheet hoja1 = objLibro.createSheet("hoja 1");

// Proceso la información y genero el xls.



HSSFFont fuente = objLibro.createFont();
fuente.setFontHeightInPoints((short)11);
fuente.setFontName(fuente.FONT_ARIAL);
fuente.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

// Luego creamos el objeto que se encargará de aplicar el estilo a la celda
HSSFCellStyle estiloCelda = objLibro.createCellStyle();
estiloCelda.setWrapText(true);
estiloCelda.setAlignment(HSSFCellStyle. ALIGN_JUSTIFY);
estiloCelda.setVerticalAlignment(HSSFCellStyle.VERTICAL_TOP);
estiloCelda.setFont(fuente);

// También, podemos establecer bordes...
estiloCelda.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM);
estiloCelda.setBottomBorderColor((short)8);
estiloCelda.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);
estiloCelda.setLeftBorderColor((short)8);
estiloCelda.setBorderRight(HSSFCellStyle.BORDER_MEDIUM);
estiloCelda.setRightBorderColor((short)8);
estiloCelda.setBorderTop(HSSFCellStyle.BORDER_MEDIUM);
estiloCelda.setTopBorderColor((short)8);

// Establecemos el tipo de sombreado de nuestra celda
estiloCelda.setFillForegroundColor((short)01);
estiloCelda.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

// Creamos la celda, aplicamos el estilo y definimos
// el tipo de dato que contendrá la celda
for(int i =0;i<10; i++){
HSSFRow fila = hoja1.createRow((short)i);
if(i==4 || i==8){
for(int j =0;j<4; j++){
HSSFCell celda = fila.createCell((short)j);
// celda.setCellStyle(estiloCelda);
//celda.setCellType(HSSFCell.CELL_TYPE_STRING);
// Finalmente, establecemos el valor
//celda.setCellValue("Un valor");
}
}else{
for(int j =0;j<4; j++){
HSSFCell celda = fila.createCell((short)j);
celda.setCellStyle(estiloCelda);
celda.setCellType(HSSFCell.CELL_TYPE_STRING);
// Finalmente, establecemos el valor
celda.setCellValue("Un valor");
}
}





}

// Volcamos la información a un archivo.
String strNombreArchivo = "C:/libro1.xls";
File objFile = new File(strNombreArchivo);
FileOutputStream archivoSalida = new FileOutputStream(objFile);
objLibro.write(archivoSalida);
archivoSalida.close();



}catch(IOException e){
System.out.println("Error al escribir el fichero.");
}
}

public static void leerExcel()
{
try
{
//Se abre el fichero Excel
POIFSFileSystem fs =
new POIFSFileSystem(
new FileInputStream("c:/ejemplo.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);

//Se leen las primeras 5 celdas
for(int i=0; i<5; i++)
{
//Se obtiene la celda i-esima
HSSFCell cell = row.getCell((short)i);

//Si la celda leida no está vacía
if (cell != null)
{
//Se imprime en pantalla la celda según su tipo
switch(cell.getCellType())
{
case HSSFCell.CELL_TYPE_NUMERIC:
System.out.println("Número: " + cell.getNumericCellValue());
break;
case HSSFCell.CELL_TYPE_STRING:
System.out.println("String: " + cell.getStringCellValue());
break;
case HSSFCell.CELL_TYPE_BOOLEAN:
System.out.println("Boolean: " + cell.getBooleanCellValue());
break;
default:
System.out.println("Default: " + cell.getDateCellValue());
break;
}
}
}
}
catch(IOException ex)
{
System.out.println("Error al leer el fichero.");
}
}
}

Comentarios

Publicar un comentario

Entradas populares de este blog

Primer CodeLab de Web Services con Mule ESB, JAX WS, SOAP, WSDL, Spring

Primer CodeLab de Web Services usando [ Mule ESB , JAX WS , SOAP , WSDL , Spring ]. en este post no hablaré nada teórico sobre Mule , ya que ello lo pueden encontrar Googleando, será un lab totalmente práctico. Requisitos: - JDK  1.6 - MuleStudio - soapUI Paso a Paso para crear Web Services con Mule : 1. Crear proyecto Mule ( MuleStudio ):  Next > Next > Next > Finish 2.- Crear el Objeto Producto.java package com.dmotta.mule.labuno.mulelabuno.bo; import java.io.Serializable; public class Producto implements Serializable { private String id; private String nombre; private String marca; private String descripcion; public Producto() { } public Producto(String id, String nombre, String marca, String descripcion) { this.id=id; this.nombre=nombre; this.marca=marca; this.descripcion=descripcion; } //getters/setters } 3.- Crear la Interface que publicará los métodos listarProductos() y getDetalleProdu...

RESTful Webservices con Java (Jersey / JAX-RS) - Tutorial Uno

REST con Java (JAX-RS) usando Jersey Este articulo explica como desarrollar RESTful web services en Java con JAX-RS implementacion de Jersey. En este ejemplo se usara SpringSource Tools Suite(Eclipse Helios), Java 1.6, SpringSource TC Server and JAX-RS 1.1. (Jersey 1.4). 1. REST - Representational State Transfer 1.1 Informacion General: En una Arquitectura REST tipicamente se tiene un REST server , el cual provee acceso a los Clientes REST  que acceden a consultar, modificar un Recurso REST . REST permite que los recursos sean presentados en diferentes tipos de datos, "text, html, xml, JSON" .  El Cliente REST  puede generar una peticion de un tipo de dato via el protocolo HTTP. 1.2. HTTP metodos Los metodos estandar HTTP usados en en REST son  PUT, GET, POST, DELETE. 1.3. RESTFul webservices Un RESTFul webservices es basados en metodos HTTP y en el concepto REST.  Por lo general se define URI base para los servicios, los MIME-types sus...